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-catch will do is catch exceptions occurring in the call to schedule, 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:
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
ScheduledFuture f = exec.scheduleWithFixedDelay(new Task(arg1, arg2), 0,
RETRY_PERIOD, TimeUnit.MILLISECONDS);
...
try {
f.get(); // wait for task to finish
} catch(ExecutionException ex) {
System.out.println("Exception caught");
}
where Task is a class that implements Runnable.
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.