下面我们看主线程如何捕获子线程的异常
例:1.5.4
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("在子线程,我自己抛出的一个异常");
}
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++)
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44639795/article/details/103096660