Handling Exceptions in ExecutorService

This program demonstrates handling exceptions in ExecutorService tasks.

Problem Statement

Write a Java program that handles exceptions in tasks submitted to ExecutorService.

Source Code

1 import java.util.concurrent.*;
2 public class ExecutorExceptionExample {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Executor Exception Example");
5 ExecutorService es=Executors.newSingleThreadExecutor();
6 Future<Integer> f=es.submit(() -> 10/0);
7 try {
8 System.out.println("Eduinq Result: "+f.get());
9 } catch(Exception e) {
10 System.out.println("Eduinq Exception: "+e.getMessage());
11 }
12 es.shutdown();
13 }
14 }

Program Output

					Eduinq Executor Exception Example
Eduinq Exception: java.lang.ArithmeticException: / by zero
				

Explanation

Exceptions in executor tasks are wrapped in ExecutionException. - Caller must handle exceptions when retrieving results. - Improves reliability in concurrent execution. - In enterprise systems, executor exception handling ensures safe task management. Conclusion: Shows handling exceptions in ExecutorService.

Quick Links to Explore