我们经常碰到线程突然死掉,但是又找不到原因,总不能在每个线程的run方法中都加上Try Catch吧, 况且对第三方框架内启的线程你想加Try catch还加不了呢? 怎么办?
现在有一个现成的办法,就是给每个线程"加个"默认的Try Catch, 任意一个线程出现没有捕获住的异常都执行我们自定义的那段代码。Thread中提供一个 setDefaultUncaughtExceptionHandler 的静态方法,给我们提供了这种可能。
代码贴出来如下:
class ExceptionHandler implements UncaughtExceptionHandler{
private final Logger logger = Logger.getLogger("Exception");
ExceptionHandler(){
FileHandler myFileHandler;
try {
myFileHandler = new FileHandler ("D:\\Logger.log");
SimpleFormatter formatter = new SimpleFormatter();
logger.addHandler(myFileHandler);
myFileHandler.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.log(Level.ALL, "UncaughtException Thread ");
}
}
UncaughtExceptionHandler handle=new ExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(handle);
在程序启动的时候加入这一段。这样任何线程中,只有有没有被捕获的异常,都会执行我自定义的Handle的uncaughtException方法,把这个异常打印出来。
本文介绍了一种在Java中全局捕获未处理线程异常的方法,通过设置默认的未捕获异常处理器来确保所有线程中的未捕获异常都能被记录下来。
966

被折叠的 条评论
为什么被折叠?



