无法从TimerTask线程捕获异常 [英] Unable to catch exception from TimerTask thread

查看:475
本文介绍了无法从TimerTask线程捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类,该类在其main方法中启动TimerTask,扩展TimerTask的类是一个内部类(类myTimer扩展TimerTask).在其运行方法myTimer中引发异常,在主要方法中,我试图捕获如下异常:

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");
}

但是这行不通,它永远不会捕获myTimer线程引发的异常.任何想法如何做到这一点?

But this doesn't work, it never catches the exception, myTimer thread throws. Any ideas how to do that ?

推荐答案

您的情况有些棘手,并且我不确定您期望在代码段中发生什么.您是否希望主线程在计时器线程引发异常之前一直阻塞?因为那不会发生. try-catch唯一要做的是捕获对schedule的调用中发生的异常,而不是线程定期执行的代码中的异常.

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.

使用ScheduledThreadPoolExecutor可以轻松实现后一种情况:

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");
}

其中Task是实现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.

这篇关于无法从TimerTask线程捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆