title: Handling exceptions from Java ExecutorService tasks
body: <p>I'm trying to use Java's <code>ThreadPoolExecutor</code> class to run a large number of heavy weight tasks with a fixed number of threads. Each of the tasks has many places during which it may fail due to exceptions.</p>
  
  <p>I've subclassed <code>ThreadPoolExecutor</code> and I've overridden the <code>afterExecute</code> method which is supposed to provide any uncaught exceptions encountered while running a task. However, I can't seem to make it work.</p>
  
  <p>For example:</p>
  
  <pre><code>public class ThreadPoolErrors extends ThreadPoolExecutor {
      public ThreadPoolErrors() {
          super(  1, // core threads
                  1, // max threads
                  1, // timeout
                  TimeUnit.MINUTES, // timeout units
                  new LinkedBlockingQueue&lt;Runnable&gt;() // work queue
          );
      }
  
      protected void afterExecute(Runnable r, Throwable t) {
          super.afterExecute(r, t);
          if(t != null) {
              System.out.println("Got an error: " + t);
          } else {
              System.out.println("Everything's fine--situation normal!");
          }
      }
  
      public static void main( String [] args) {
          ThreadPoolErrors threadPool = new ThreadPoolErrors();
          threadPool.submit( 
                  new Runnable() {
                      public void run() {
                          throw new RuntimeException("Ouch! Got an error.");
                      }
                  }
          );
          threadPool.shutdown();
      }
  }
  </code></pre>
  
  <p>The output from this program is "Everything's fine--situation normal!" even though the only Runnable submitted to the thread pool throws an exception. Any clue to what's going on here?</p>
  
  <p>Thanks!</p>