I have the following code that I expect to run successfully to completion but the code fails at the line "fail("this should not be reached");". Can someone please explain why the default uncaught exception handler is not called:
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);
}
}