Java并发学习之八——在线程中处理不受控制的异常

1Java里有2种异常:

检查异常:这些异常必须强制捕获她们或在一个方法里的throws子句中。

未检查异常:这些异常不用强制捕获它们。

2、在一个线程对象的run()方法里抛出一个检查异常,我们必须捕获并处理她们。因为run()方法不接受throws子句。当一个非检查异常抛出,默认的的行为是在控制台写下stack trace并退出程序。

package chapter;  
  
public class Main8 {  
  
    /** 
     * <p> 
     * </p> 
     * @author zhangjunshuai 
     * @date 2014-8-21 下午2:14:52 
     * @param args 
     */  
    public static void main(String[] args) {  
  
        Task task = new Task();  
        Thread thread = new Thread(task);  
        thread.setUncaughtExceptionHandler(new ExceptionHandler());  
        thread.start();  
    }  
  
}  
package chapter;  
  
public class Task implements Runnable{  
    @Override  
    public void run() {  
  
        int numero = Integer.parseInt("TTT");  
    }  
  
}
package chapter;  
  
import java.lang.Thread.UncaughtExceptionHandler;  
  
public class ExceptionHandler implements UncaughtExceptionHandler{  
  
    @Override  
    public void uncaughtException(Thread t, Throwable e) {  
  
        System.out.printf("An exception has been captured\n");  
        System.out.printf("Thread:%s\n",t.getId());  
        System.out.printf("Exception:%s :%s\n",e.getClass().getName(),e.getMessage());  
        System.out.printf("Stack Traace");  
        e.printStackTrace(System.out);  
        System.out.printf("Thread status:%s\n",t.getState());  
          
    }  
  
}

posted @ 2017-07-27 11:33  十月围城小童鞋  阅读(109)  评论(0)    收藏  举报