Course contentsShow
← Java
Lesson 2734 of 2,87050. Executor FrameworkFree lesson

Exception Handling with submit: Future.get Throws

How submit captures exceptions and throws ExecutionException when Future.get is called.

Exception Handling with submit: Future.get Throws

You'll learn how submit() captures exceptions from tasks and re-throws them when you call Future.get(), giving you explicit control over error handling.

The Key Difference from execute

While execute() silently swallows exceptions (as you learned in the previous lesson), submit() takes a different approach: it captures any exception thrown by your task and stores it inside the returned Future object. The exception won't surface until you call Future.get().

How It Works

When your submitted task throws an exception:

  1. The exception is caught by the Executor framework
  2. It's wrapped in an ExecutionException
  3. It remains dormant inside the Future
  4. When you call Future.get(), the ExecutionException is thrown to you
  5. You can retrieve the original exception using getCause()
ExecutorService executor = Executors.newFixedThreadPool(2);

Future<?> future = executor.submit(() -> {
    throw new IllegalArgumentException("Something went wrong!");
});

try {
    future.get(); // Blocks until task completes or fails
} catch (ExecutionException e) {
    System.out.println("Task threw: " + e.getCause().getMessage());
    // Prints: Task threw: Something went wrong!
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

executor.shutdown();

Why This Is Better

This approach forces you to explicitly acknowledge that errors might occur. You can't accidentally ignore exceptions—you must handle them when retrieving results. This makes submit() far safer for production code where error handling matters.

Think of it like ordering food delivery: execute() is leaving a note on the door and walking away, while submit() gives you a tracking number you must check to see if delivery succeeded or failed.

Key Takeaway: submit() captures task exceptions and wraps them in ExecutionException, which is thrown when you call Future.get(), giving you explicit, unavoidable error handling.