线程内部抛出的异常无法捕获
由于线程的本质特性,使得你不能捕获从线程中逃逸的异常。《Java编程思想》
代码示例:
public static void main(String[] args) {
try {
new Thread(new Runnable() {
@Override
public void run() {
throw new NullPointerException();
}
}).start();
} catch (Exception e) {
System.out.println("Catch an exception!");
}
}
输出:
Exception in thread "Thread-0" java.lang.NullPointerException
at Test$1.run(Test.java:10)
at java.lang.Thread.run(Unknown Source)
由此可见,在线程中抛出的异常的确无法进行捕获处理。其实仔细想想也容易理解,各人自扫门前雪嘛。
如何处理线程内部异常
本着【各人自扫门前雪】的思路,如果需要的话,线程内部异常还需线程自身进行捕获。
第一种方式
在线程内部通过try catch 语句块进行捕获处理。
例:
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
throw new NullPointerException();
} catch (Exception e) {
System.out.println("Catch an exception!");
}
}
}).start();
}
结果:
Catch an exception!
第二种方式
为线程指定异常处理器。
Thread.UncaughtExceptionHandler是Thread类中的一个内部接口,当线程因未捕获异常而濒临死亡时会调用Thread.UncaughtExceptionHandler.unCaughtException()。
例:
public static void main(String[] args) {
Thread mThread =
new Thread(new Runnable() {
@Override
public void run() {
throw new NullPointerException();
}
});
mThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// TODO Auto-generated method stub
System.out.println("Catch an exception!");
}
});
mThread.start();
}
结果:
Catch an exception!