我不確定這是你在找什麼,但有一個終止線程的異常處理程序。它是任何異常的處理程序,不會被線程的目標顯式捕獲。
默認的「未捕獲的異常處理程序」只需調用就可以將堆棧跟蹤打印到System.err
。但是,你可以replace這個跟自己UncaughtExceptionHandler
它記錄的異常,而不是結果到log4j:
class Log4jBackstop implements Thread.UncaughtExceptionHandler {
private static Logger log = Logger.getLogger(Log4jBackstop.class);
public void uncaughtException(Thread t, Throwable ex) {
log.error("Uncaught exception in thread: " + t.getName(), ex);
}
}
如果您使用的是執行框架,其中傳遞一個Runnable
對象,它的線程可能有自己的catch
塊防止到達未捕獲的異常處理程序的異常。如果你想趕上Runtime
例外存在,做一個方式,它是包裝每一個任務在日誌的包裝,像這樣:
class Log4jWrapper {
private final Logger log;
private final Runnable target;
Log4jWrapper(Logger log, Runnable target) {
this.log = Objects.requireNonNull(log);
this.target = Objects.requireNonNull(target);
}
public void run() {
try {
target.run();
} catch(RuntimeException ex) {
log.error("Uncaught exception.", ex);
throw ex;
}
}
}
...
Runnable realTask = ...;
executor.submit(new Log4jWrapper(Logger.getLogger(Whatever.class), realTask));
你的意思是「未捕獲」 RuntimeExceptions? – 2010-02-26 20:43:43
是的我的意思是「未被捕獲」RuntimeExceptions – DkS 2010-02-26 20:58:26