简体   繁体   中英

Unable to catch exception from TimerTask thread

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 ?

The Timer will be executing the TimerTask.run() method in a different thread from the the thread that added it, the main method the parent class will not able to catch the thrown exception.

A possible solution would be to prevent the exception from propagating out of the run() method and make any useful information available to the parent via some query method. The parent would be required to wait for the run() method to complete before querying for the result.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM