title: Catching thread exceptions from Java ExecutorService
body: <p>I'm working on a software development framework for parallel computing <a href="http://javaseis.org" rel="noreferrer">JavaSeis.org</a>. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?</p>
  
  <pre><code>import java.util.concurrent.Callable;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.concurrent.Future;
  
  public class TestThreadFailure {
  
    public static void main(String[] args) {
      int size = 1;
      ExecutorService exec = Executors.newFixedThreadPool(size);
      ThreadFailTask worker = new ThreadFailTask();
      Future&lt;Integer&gt; result = exec.submit(worker);
      try {
        Integer value = result.get();
        System.out.println("Result: " + value);
      } catch (Throwable t) {
        System.out.println("Caught failure: " + t.toString());
        exec.shutdownNow();
        System.out.println("Stack Trace:");
        t.printStackTrace();
        return;
      }
      throw new RuntimeException("Did not catch failure !!");
    }
  
    public static class ThreadFailTask implements Callable&lt;Integer&gt; {
      @Override
      public Integer call() {
        int nbuf = 65536;
        double[][] buf = new double[nbuf][nbuf];
        return new Integer((int) buf[0][0]);
      }
    }
  }
  </code></pre>