Est-il possible d'attacher un UncaughtExceptionHandler à un TimerTask? (Autres qu'en l'appelant Thread.setDefaultUncaughtExceptionHandler())Attacher UncaughtExceptionHandler à un TimerTask
Vive
Rich
Est-il possible d'attacher un UncaughtExceptionHandler à un TimerTask? (Autres qu'en l'appelant Thread.setDefaultUncaughtExceptionHandler())Attacher UncaughtExceptionHandler à un TimerTask
Vive
Rich
Vous pouvez écrire un proxy TimerTask
qui attire Throwable
de 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: Vous voudrez peut-être envisager d'utiliser java.util.concurrent
au lieu de Timer
.
Oui, je le pense. Il existe une méthode d'instance (setUncaughtExceptionHandler) dans Thread
class
qui définit UncaughtExceptionHandler
du fil.
Dans votre méthode run
du TimerTask
que vous pouvez faire quelque chose comme ceci:
public void run() {
Thread.currentThread().setUncaughtExceptionHandler(eh);
}