问题
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);
}
};
回答1:
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);
来源:https://stackoverflow.com/questions/24105323/catch-exception-for-executor-thread-pool