title: How to use an uncaught exception handler for a multi-thread test in junit?
body: <p>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:</p>
  
  <pre><code>public class UncaughtExceptionTest extends TestCase
      implements UncaughtExceptionHandler {
  
      private final List&lt;Throwable&gt; uncaughtExceptions =
          new CopyOnWriteArrayList&lt;Throwable&gt;();
  
      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() &gt; 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);
      }
  }
  </code></pre>