Java线程:运行方法不能抛出检查异常 [英] Java Thread: Run method cannot throw checked exception

查看:290
本文介绍了Java线程:运行方法不能抛出检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java线程中,'run'方法不能抛出'checked exception'。我在Core Java(第1卷)书中遇到过这个。有人可以解释一下背后的推理吗?

In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1) book. Can someone please explain the reasoning behind it?

推荐答案


有人可以解释背后的推理吗?

Can someone please explain the reasoning behind it?

是的,因为任何引发运行方法的异常将被JVM仔细忽略。因此,抛出它可能是一个错误(除非你有线程的特定异常处理程序,请参阅文档)。没有理由煽动潜在的错误行为。

Yes, because any exception you throw in run method will be carefully ignored by JVM. Thus, throwing it there is probably a mistake (unless you have specific exception handler for the thread, see the docs about that). No reason to incite potentially erroneous behaviour.

或者举个例子。

 class MyThread extends Thread {
     public void run() {
         throw new RuntimeException();
     }
 }

...

new MyThread().start();
// here thread dies silently with no visible effects at all

/ strong>

edit


为什么父线程不能捕获生成的子线程的异常?

Why can't the parent thread 'catch' the exception from the spawned 'child' thread?

@ chaotic3quilibrium 在他的评论中已经注意到为什么不:因为父线程已经有可能已经移动了。

@chaotic3quilibrium has already noted in his comment why not: because parent thread has likely moved on already.

new MyThread().start(); // launch thread and forget

// 1000 lines of code further...
i = i + 1; // would you like exception from child thread to be propagated here?

这篇关于Java线程:运行方法不能抛出检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆