I have a Java class which starts a TimerTask in its main method, the class extending TimerTask is an inner class (Class myTimer extends TimerTask). In its run method myTimer throws an exception, In the main method I am trying to catch the exception like this:
try {
timer.schedule(new myTimer(arg1, arg2), 0, RETRY_PERIOD);
} catch (Exception e) {
System.out.println("Exception caught");
}
But this doesn’t work, it never catches the exception, myTimer thread throws. Any ideas how to do that ?
Your situation is a bit tricky and I’m not sure what you expect to happen in your code snippet. Do you expect the main thread to block until the timer thread throws an exception? Because that will not happen. The only thing that
try-catchwill do is catch exceptions occurring in the call toschedule, not in the code executed by the thread periodically.It would not make sense anyway. Since a timer thread can throw an exception in parallel with the main thread, you would need to either freeze the main thread periodically to check for exceptions or freeze it permanently until the timer finishes.
The latter case can be easily done with a
ScheduledThreadPoolExecutor:where
Taskis a class that implementsRunnable.Of course, this will block the main thread until the task returns or throws an exception (which might never happen). Alternatively you can use the timed get to check periodically for exceptions.