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:
- The exception is caught by the Executor framework
- It's wrapped in an
ExecutionException - It remains dormant inside the
Future - When you call
Future.get(), theExecutionExceptionis thrown to you - 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.