Java異常與線程
如何使用線程異常?
解決方法
這個例子顯示了如何處理異常及處理線程。
class MyThread extends Thread{ public void run(){ System.out.println("Throwing in " +"MyThread"); throw new RuntimeException(); } } class Main { public static void main(String[] args){ MyThread t = new MyThread(); t.start(); try{ Thread.sleep(1000); } catch (Exception x){ System.out.println("Caught it" + x); } System.out.println("Exiting main"); } }
結果
上麵的代碼示例將產生以下結果。
Throwing in MyThread Exception in thread "Thread-0" java.lang.RuntimeException at testapp.MyThread.run(Main.java:19) Exiting main