java中对于多线程程序的捕获异常的方案

在并发的情况下,try{}catch{Exception ex}不能捕获一般的异常处理,这会导致在异常产生时会直接将异常输出到控制台或者是用户界面,在java5中加入了一些接口来解决这个问题,下面为简单的事例

 

[java]  view plain copy print ?
  1. package com.eric.concurrency;  
  2.   
  3. import java.lang.Thread.UncaughtExceptionHandler;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6.   
  7. /** 
  8.  * 这个程序主要掩饰了在程序中队Runnable异常的捕获方法 
  9.  *  
  10.  * @author Eric 
  11.  *  
  12.  */  
  13. public class ExceptionThread {  
  14.       
  15.     public static void main(String[] args) {  
  16.         try {  
  17.             CatchException.catchExceptionByUncaughtExceptionHandler();  
  18.             System.out.println("************************************");  
  19.             // CatchException.catchExceptionByCatch();  
  20.         } catch (Exception ex) {  
  21.             // ex.printStackTrace();  
  22.         }  
  23.     }  
  24. }  
  25.   
  26. class ExceptionRunnable implements Runnable {  
  27.     public void run() {  
  28.         throw new RuntimeException("Throw By Runnable");  
  29.     }  
  30.       
  31. }  
  32.   
  33. // 用普通的catch方法捕获  
  34. class CatchException {  
  35.     public static void catchExceptionByCatch() {  
  36.         ExecutorService es = Executors.newCachedThreadPool();  
  37.         es.execute(new ExceptionRunnable());  
  38.           
  39.     }  
  40.       
  41.     /* 
  42.      * use try{} catch{} block can't catch exception from Runnable,to solve the 
  43.      * problem. Thread.UncaughtExceptionHandler is a new interface in Java SE5; 
  44.      * it allows you o attach an exception handler to each Thread object. 
  45.      * Thread.UncaughtExceptionHandler.uncaughtException( ) is automatically 
  46.      * called when that thread is about to die from an uncaught exception. 
  47.      */  
  48.     public static void catchExceptionByUncaughtExceptionHandler() {  
  49.         Thread t = new Thread(new ExceptionRunnable());  
  50.         t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {  
  51.               
  52.             @Override  
  53.             public void uncaughtException(Thread t, Throwable e) {  
  54.                 System.out.println("Exception:" + e.getMessage() + " was catched");  
  55.             }  
  56.         });  
  57.         t.start();  
  58.     }  
  59. }  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值