我有以下代码,我希望这些代码能够成功运行到完成,但代码在"fail("this not be reached");“行失败。谁能解释一下为什么不调用默认的未捕获异常处理程序:
public class UncaughtExceptionTest extends TestCase
implements UncaughtExceptionHandler {
private final List<Throwable> uncaughtExceptions =
new CopyOnWriteArrayList<Throwable>();
class UncaughtExceptionTestInnerClass implements Runnable {
private final ScheduledThreadPoolExecutor executor =
new ScheduledThreadPoolExecutor(1);
private final CountDownLatch latch;
UncaughtExceptionTestInnerClass(CountDownLatch latch) {
this.latch = latch;
executor.schedule(this, 50, TimeUnit.MILLISECONDS);
}
@Override
public void run() {
System.out.println("This is printed");
fail("this should fail");
latch.countDown();
}
}
@Test
public void testUncaughtExceptions() {
Thread.setDefaultUncaughtExceptionHandler(this);
CountDownLatch latch = new CountDownLatch(1);
UncaughtExceptionTestInnerClass testTheInnerClass =
new UncaughtExceptionTestInnerClass(latch);
try {
if (!latch.await(1, TimeUnit.SECONDS)) {
if (uncaughtExceptions.size() > 0) {
Throwable exception = uncaughtExceptions.get(0);
System.out.println("First uncaught exception: " +
exception.getMessage());
}
else {
fail("this should not be reached");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void uncaughtException(Thread t, Throwable e) {
uncaughtExceptions.add(e);
}
}发布于 2010-07-02 12:30:28
这与您使用Executor来运行任务的事实有关。只有当线程由于未捕获的异常而将要终止时,才调用未捕获的异常处理程序。如果您将实现更改为使用普通线程,则线程将以异常终止,您将看到预期的行为。
根据您提交任务的方式,executor线程可能会捕获所有Throwable并处理它们。因此,线程不会因为这些异常而终止,因此不涉及未捕获的异常处理程序。例如,ThreadPoolExecutor.execute(Runnable)将触发未捕获的异常处理程序。但是,ThreadPoolExecutor.submit(Callable)不需要。此外,ScheduledThreadPoolExecutor.schedule()也不需要(这与他们使用FutureTask实现有关)。
使用executor服务访问意外异常的更好方法是通过Future。
发布于 2011-08-31 12:27:59
ScheduledThreadPoolExecutor.schedule()接受Runnable/Callable参数,而不是Thread。前者没有运行时异常处理程序。在您的run或call方法中为RuntimeException设置一个try/catch块。
https://stackoverflow.com/questions/3163117
复制相似问题