I have a ScheduledThreadPoolExecutor that seems to be eating Exceptions. I want my executor service to notify me if a submitted Runnable throws an exception.
For example, I'd like the code below to at the very least print the IndexArrayOutOfBoundsException's stackTrace
threadPool.scheduleAtFixedRate(
new Runnable() {
public void run() {
int[] array = new array[0];
array[42] = 5;
}
},
1000,
1500L,
TimeUnit.MILLISECONDS);
As a side question. Is there a way to write a general try catch block for a ScheduledThreadPoolExecutor?
//////////END OF ORIGINAL QUESTION //////////////
As suggested the following Decorator works well.
public class CatcherTask implements Runnable{
Runnable runMe;
public CatcherTask(Runnable runMe) {
this.runMe = runMe;
}
public void run() {
try {
runMe.run();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
I wrote a small post about this problem a while ago. You have two options:
UncaughtExceptionHandler
you wrap each submitted runnable into a runnable of your own which executes (calls run
) the real runnable inside a try-catch-block.EDIT
As pointed out by Mark, it's important to wrap the Runnable
passed to ScheduledExecutorService
instead of the one passed to the ThreadFactory
.