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(); } } }
You can subclass ScheduledThreadPoolExecutor and override the afterExecute method to handle exceptions and errors for any kind of Runnable that you submit. Show activity on this post. Consider adding a static event in your ScheduledThreadPoolExecutor class that any of your tasks can call if an exception is thrown.
Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.
don't handle any exceptions in the dao layer, instead throw it to the front-end and handle it. to handle the exception all you need to do is to catch the appropriate exception in the hierarchy and address it.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With