Hi
Is it possible to attach an UncaughtExceptionHandler to a TimerTask? (Other than by calling Thread.setDefaultUncaughtExceptionHandler())
Cheers
Rich
Hi
Is it possible to attach an UncaughtExceptionHandler to a TimerTask? (Other than by calling Thread.setDefaultUncaughtExceptionHandler())
Cheers
Rich
You can write a TimerTask
proxy that catches Throwable
from run
.
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() {
return orig.cancel();
}
@Override public void run() {
try {
orig.run();
} catch (Throwable exc) {
handler.uncaughtException(Thread.currentThread(), exc);
}
}
@Override public long scheduledExecutionTime() {
return orig.scheduledExecutionTime();
}
}
BTW: You might want to consider using java.util.concurrent
instead of Timer
.
Yes, I think so. There's an instance method (setUncaughtExceptionHandler) in Thread
class
that set's the thread's UncaughtExceptionHandler
.
In your run
method of the TimerTask
you can do something like this:
public void run() {
Thread.currentThread().setUncaughtExceptionHandler(eh);
}