在Java程式設計中,如何使用執行緒異常?
此範例顯示如何在處理執行緒時處理異常。
package com.yiibai;
class MyThread extends Thread {
public void run() {
System.out.println("Throwing in " + "MyThread");
throw new RuntimeException();
}
}
public class ExceptionWithThread {
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 MyThreadException in thread "Thread-0"
java.lang.RuntimeException
at com.yiibai.MyThread.run(ExceptionWithThread.java:6)
Exiting main