`
Mybeautiful
  • 浏览: 294377 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

从源头上捕获线程中产生的异常

阅读更多

    我们经常碰到线程突然死掉,但是又找不到原因,总不能在每个线程的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方法,把这个异常打印出来。

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics