在 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/