java中給出一個(gè)主線程如何捕獲子線程異常的例子
馬克-to-win:下面我們看主線程如何捕獲子線程的異常
例:1.5.4-本章源碼
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
import java.lang.Thread.UncaughtExceptionHandler;
class ThreadMark_to_win extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("在子線程"+i);
}
throw new RuntimeException("在子線程,我自己拋出的一個(gè)異常");
}
String getMyName()
{
return "馬克-to-win在子線程";
}
}
public class Test
{
public static void main(String[] args)
{
ThreadMark_to_win tm = new ThreadMark_to_win();
tm.setUncaughtExceptionHandler(new UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("在主程序處理呢 "+((ThreadMark_to_win)t).getMyName() + " : " + e.getMessage());
}
});
tm.start();
for(int i=0;i<10;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("在主線程"+i);
}
}
}
輸出結(jié)果:
在主線程0
在子線程0
在主線程1
在子線程1
在子線程2
在主線程2
在主程序處理呢 馬克-to-win在子線程 : 在子線程,我自己拋出的一個(gè)異常
在主線程3
在主線程4
在主線程5
在主線程6
在主線程7
在主線程8
在主線程9
后續(xù):
馬克-to-win:主線程通過tm.setUncaughtExceptionHandler這種方法,設(shè)置了一個(gè)Handler(所謂的處理器)這個(gè)處理器處理tm的uncaughtException(未捕獲的異常)。