歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中主線程如何捕獲子線程拋出的異常

Java中主線程如何捕獲子線程拋出的異常

日期:2017/3/1 10:37:05   编辑:Linux編程
這麼來看待這個問題。首先明確線程代碼的邊界。其實很簡單,Runnable接口的run方法所界定的邊界就可以看作是線程代碼的邊界。Runnable接口中run方法原型如下:
<<
public void run();
>>
而所有的具體線程都實現這個方法,所以這裡就明確了一點,線程代碼不能拋出任何checked異常。所有的線程中的checked異常都只能被線程本身消化掉。:) 這樣本身也是符合線程的設計理念的,線程本身就是被看作獨立的執行片斷,它應該對自己負責,所以由它來消化所有的checked異常是很正常的。
這樣就回答了樓主的第一個問題:checked異常一定要在線程內部消化。

但是,線程代碼中是可以拋出錯誤(Error)和運行級別異常(RuntimeException)的。Error俺們可以忽略,因為通常Error是應該留給vm的,而RuntimeException確是比較正常的,如果在運行過程中滿足了某種條件導致線程必須中斷,可以選擇使用拋出運行級別異常來處理,如下:
<<
public void run() {
if (...) throw new RuntimeException();
}
>>
當線程代碼拋出運行級別異常之後,線程會中斷。:)這點java中解釋得很清楚:
<< @see Thread
All threads that are not daemon threads have died, either by returning from the call to the run method or "by throwing an exception that propagates beyond the run method".
>>
但是對於invoke此線程的主線程會產生什麼影響呢?主線程不受這個影響,不會處理這個RuntimeException,而且根本不能catch到這個異常。會繼續執行自己的代碼
所以得到結論:線程方法的異常只能自己來處理。

關於最後一點,不相信的話大家可以做這麼一個試驗:
<<
public class TestThreadException extends Thread {
public void run() {
throw new RuntimeException();
}

public static void main(String[] args) throws InterruptedException {
try {
new TestThreadException().start();
} catch(RuntimeException ex) {
// 看看能不能到達這裡?
}

Thread.sleep(1000);
// 看看能不能到達這裡?
}
}
>>


記不得在哪裡看到的代碼,可以處理到線程中拋出的RuntimeException:

public class ApplicationLoader extends ThreadGroup
{
private ApplicationLoader()
{

super("ApplicationLoader");

}

public static void main(String[] args)
{

Runnable appStarter = new Runnable()
{

public void run()
{
//invoke your application (i.e.MySystem.main(args)

throw new NullPointerException(); //example, throw a runtime exception
}
};

new Thread(new ApplicationLoader(), appStarter).start();
}

//We overload this method from our parent
//ThreadGroup , which will make sure that it
//gets called when it needs to be. This is
//where the magic occurs.
public void uncaughtException(Thread thread, Throwable exception)
{
//Handle the error/exception.
//Typical operations might be displaying a
//useful dialog, writing to an event log, etc.

exception.printStackTrace();//example, print stack trace
}
}


呵呵,uncaughtException好像是唯一能夠處理線程拋出的uncaught異常的入口。看來還是有細心人啊。確實如此,通過ThreadGroup的uncaughtException方法還是有處理的機會。當線程拋出uncaughtException的時候,JVM會調用ThreadGroup的此方法。默認的處理如下:
<<
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
e.printStackTrace(System.err);
}
}
>>
每個Thread都會有一個ThreadGroup對象,可以通過Thread.getThreadGroup()方法得到,提供了上述默認的uncaught異常處理方法。
上面沒有提這點,因為俺認為在正常的情況下,這個方法的處理情況就已經足夠了。還是那個線程設計的理念:“線程的問題應該線程自己本身來解決,而不要委托到外部。”通常情況下,外部不需要處理線程的異常。當然也有例外。:)
Copyright © Linux教程網 All Rights Reserved