Java - Handle Exception from Future's get() Method

Description

Handle Exception from Future's get() Method

Demo

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) {
    Callable<Object> badTask = () -> {
      throw new RuntimeException("Throwing exception from task execution...");
    };/* w  w w  . j a  v  a 2 s  .  c  om*/

    // CReate an executor service
    ExecutorService exec = Executors.newSingleThreadExecutor();

    // Submit a task
    Future submittedTask = exec.submit(badTask);

    try {
      // The get method should throw ExecutionException
      Object result = submittedTask.get();
    } catch (ExecutionException e) {
      System.out.println("Execution exception has occurred: " + e.getMessage());
      System.out.println("Execution exception cause is: "
          + e.getCause().getMessage());
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    exec.shutdown();
  }
}

Result

Related Topic