java timer 捕获异常,无法从TimerTask线程捕获异常

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值