是否可以将UncaughtExceptionHandler连接到TimerTask
(不是通过调用Thread.setDefaultUncaughtExceptionHandler())
发布于 2009-04-01 15:19:05
您可以编写一个从run捕获Throwable的TimerTask代理。
public final class TimerTaskCatcher extends TimerTask {
private final TimerTask orig;
private final Thread.UncaughtExceptionHandler handler;
public TimerTaskCatcher(
TimerTask orig,
Thread.UncaughtExceptionHandler handler
) {
if (orig == null || handler == null) {
throw new NullPointerException();
}
this.orig = orig;
this.handler = handler;
}
@Override public boolean cancel() {
// **Edit:** Correction report due to @Discape.
// In fact, this entire method could be elided.
boolean weirdResult;
try {
orig.cancel();
} finally {
weirdResult = super.cancel();
}
return weirdResult;
}
@Override public void run() {
try {
orig.run();
} catch (Throwable exc) {
handler.uncaughtException(Thread.currentThread(), exc);
}
}
@Override public long scheduledExecutionTime() {
return orig.scheduledExecutionTime();
}
}顺便说一句:您可能想要考虑使用java.util.concurrent而不是Timer。
发布于 2009-04-01 15:23:39
我想可以。有一个实例方法( Thread class中的setUncaughtExceptionHandler)设置了线程的UncaughtExceptionHandler。
在TimerTask的run方法中,您可以执行以下操作:
public void run() {
Thread.currentThread().setUncaughtExceptionHandler(eh);
}https://stackoverflow.com/questions/705988
复制相似问题