I have a very simple Runnable that I want to schedule for execution every 30 seconds – bear in mind that this is just a simple example for this question’s sake and not the actual point of using this in reality.
@Override
public void run() {
System.out.println("Throwing an unchecked exception on purpose...");
int abc = 123 - 123;
int def = 123 / abc;
}
I was using Timer and TimerTask but ran into a problem: whenever the TimerTask raised an unchecked exception, any subsequent execution of that task would be cancelled; thus the task above would actually only run once because it would throw an unchecked division by 0 Exception.
As far as I know, ScheduledThreadPoolExecutor has the exact same “feature”, at least according to the official Java API documentation “If any execution of the task encounters an exception, subsequent executions are suppressed”.
Is there any standard way in Java to make either Timer or ScheduledThreadPoolExecutor to don’t suppress subsequent executions if an unchecked exception is raised?
Many thanks.
Well there’s one really simple way – create an
ExceptionSuppressingRunnablewhich wraps another one:Note that this deliberately doesn’t catch
Error(or any other non-Exception subclass of Throwable). You could catchExceptioninstead ofRuntimeException– it would only make a difference in weird cases where code threw a checked exception without declaring it (due to byte code rewriting, versioning differences or whatever). I think it’s probably clearer to just catchRuntimeException.