线程中不可控制异常的处理

来源:互联网 发布:mac香港专柜地址查询 编辑:程序博客网 时间:2024/06/14 04:44

1、异常

Exception:它指出了合理的应用程序想要捕获的条件。

Exception又分为两类:一种是CheckedException(非运行时异常),一种是UncheckedException(运行时异常)。这两种Exception的区别主要是CheckedException需要用try...catch...显示的捕获,而UncheckedException不需要捕获。通常UncheckedException又叫做RuntimeException。《effective java》指出:对于可恢复的条件使用被检查的异常(CheckedException),对于程序错误(言外之意不可恢复,大错已经酿成)使用运行时异常(RuntimeException)。

常见的RuntimeExcepiton有IllegalArgumentException、IllegalStateException、NullPointerException、NumberFormatException、IndexOutOfBoundsException等等。对于那些CheckedException就不胜枚举了,在编写程序过程中try...catch...捕捉的异常都是CheckedException。io包中的IOException及其子类,ClassNotFoundException,这些都是CheckedException。

run方法不支持throws语句,所以当线程对象的run()方法抛出非运行异常时,必须捕获并且处理它们。当运行时异常从run()方法中抛出时,默认行为是在控制台输出堆栈记录并且退出程序。

2、代码事例

package com.xxx.util;/** * Created with IntelliJ IDEA. * Date: 15-3-31 * Time: 上午10:26 * To change this template use File | Settings | File Templates. */public class ThreadException implements Thread.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.println("Stack Trace:");        e.printStackTrace(System.out);        System.out.printf("Thread status:%s\n",t.getState());    }}
package com.xxx.util;/** * Created with IntelliJ IDEA. * Date: 15-3-31 * Time: 上午10:39 * To change this template use File | Settings | File Templates. */public class ThreadExceptionRun implements Runnable {    @Override    public void run() {        int i = Integer.parseInt("sss");        System.out.println(i);    }}
package com.xxx.util;/** * Created with IntelliJ IDEA. * Date: 15-3-31 * Time: 上午10:33 * To change this template use File | Settings | File Templates. */public class ThreadExceptionMain {    public static void main(String[] args){        Thread thread = new Thread(new ThreadExceptionRun());        thread.setUncaughtExceptionHandler(new ThreadException());        thread.start();    }}
3、运行结果




4、结论

java为我们提供了一种线程内发生异常时能够在线程代码边界之外处理异常的回调机制,即Thread对象提供的setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)方法。通过该方法给某个thread设置一个UncaughtExceptionHandler,可以确保在该线程出现异常时能通过回调UncaughtExceptionHandler接口的public void uncaughtException(Thread t, Throwable e) 方法来处理异常,这样的好处或者说目的是可以在线程代码边界之外(Thread的run()方法之外),有一个地方能处理未捕获异常。但是要特别明确的是:虽然是在回调方法中处理异常,但这个回调方法在执行时依然还在抛出异常的这个线程中!另外还要特别说明一点:如果线程是通过线程池创建,线程异常发生时UncaughtExceptionHandler接口不一定会立即回调。

0 0