Java 线程 : Run method cannot throw checked exception

标签 java multithreading exception

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

最佳答案

Can someone please explain the reasoning behind it?

是的,因为你在 run 方法中抛出的任何异常都会被 JVM 小心地忽略。因此,将它抛出可能是一个错误(除非您有特定的线程异常处理程序,请参阅 the docs 关于它)。没有理由煽动潜在的错误行为。

或者,举个例子。

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

...

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

编辑

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

@chaotic3quilibrium 已经在他的评论中指出了为什么不这样做:因为父线程可能已经移动了。

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 线程 : Run method cannot throw checked exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491606/

相关文章:

java - 获取 JDBC ResultSet 元数据中没有表名的 Hive 列名

java - 带有 openfire 的 SSLHandshakeException(本地主机)

java - BeanFactoryAware??它如何知道要使用哪个 beanFactory?

java - 如何仅在 处分割字符串。如果前面有双斜杠则不是?

python - 具有已发布的 GIL 和复杂线程的多线程代码在 Python 中速度较慢

c++ - 抛出异常后,对象内部分配的指针是否会自动释放?

java - JMS 与 akka 和多线程

Java:线程等待对象时是否释放所有监视器?

python - 为什么 struct.pack 会抛出一个看似没有类型的异常?

perl - 在现代 Perl 中编写异常类的最佳实践