Java线程异常逃逸与捕获

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的这种设计源自于这样一种理念:“线程是独立执行的代码片断,线程的问题应该由线程自己来解决,而不要委托到外部。”

参考文章

https://www.cnblogs.com/csniper/p/5891158.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值