Java线程内部执行异常会不会Throw?贴个代码更有说服力
package com.app.thread;
public class OThread implements Runnable {
@Override
public void run() {
System.out.print("Go to run exception !!!\r\n");
System.out.print("OThread run func Thread ID: " + Thread.currentThread().getId() + "\r\n");
throw new NullPointerException();
}
}
当在主线程中Throw NullPointer 异常时,空指针异常被捕获
package com.app.thread;
public class Test {
public static void main(String[] args) {
// 主线程
System.out.print("Main func Thread ID: " + Thread.currentThread().getId() + "\r\n");
try {
OThread thread = new OThread();
thread.run();
} catch (Exception e) {
System.out.print("Main func has cathed the exception !\r\n");
e.printStackTrace();
}
}
}
当子线程抛出异常时,这个时候主线程print日志没有输出,没有catch住异常!
package com.app.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
// 主线程
System.out.print("Main func Thread ID: " + Thread.currentThread().getId() + "\r\n");
try {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new OThread());
} catch (Exception e) {
System.out.print("Main func has cathed the exception !\r\n");
e.printStackTrace();
}
}
}
这是为什么呢?
因为在java多线程程序中,所有线程都不允许抛出未捕获的checked exception(比如sleep时的InterruptedException),也就是说各个线程需要自己把自己的checked exception处理掉。但是线程依然有可能抛出unchecked exception(如运行时异常),当此类异常跑抛出时,线程就会终结,而对于主线程和其他线程完全不受影响,且完全感知不到某个线程抛出的异常(也是说完全无法catch到这个异常)。JVM的这种设计源自于这样一种理念:“线程是独立执行的代码片断,线程的问题应该由线程自己来解决,而不要委托到外部。”
参考文章