Reputation: 11
For one thread, I catch the uncaught exception
via below code segments. However, for ExecutorService executor = Executors.newFixedThreadPool(10);
, how can I catch uncaught exception?
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Upvotes: 0
Views: 1783
Reputation: 1
Adding to above answer, you can use Executors defaultThreadFactory and adding your own uncaughtExceptionHandler. It will give better management of threads.
ExecutorService executorService = Executors.newFixedThreadPool(10, runnable -> {
Thread t = Executors.defaultThreadFactory().newThread(runnable);
t.setUncaughtExceptionHandler((Thread th, Throwable e) -> {e.printStackTrace();});
return t;
});
Upvotes: 0
Reputation: 50024
You can use the overload of the method newFixedThreadPool
, which accepts a ThreadFactory
:
Thread.UncaughtExceptionHandler eh = ...;
ThreadFactory factory = r -> {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(eh);
return t;
};
ExecutorService executor = Executors.newFixedThreadPool(10, factory);
Upvotes: 2