0

我正在运行一个 Java 守护程序并想要捕获未处理的异常。所以我写了一个类:

public class CodeineUncaughtExceptionHandler 
    implements UncaughtExceptionHandler {

  private Logger log = Logger.getLogger(CodeineUncaughtExceptionHandler.class);
  private boolean errorPrintedToOut = false;

  public CodeineUncaughtExceptionHandler() {
  }

  @Override
  public void uncaughtException(Thread t, Throwable e) {
    try {
      if (!errorPrintedToOut) {
        errorPrintedToOut = true;
        e.printStackTrace();
      }
      log.error("Uncaught exception in thread " + t.getName(), e);
    } catch (Throwable tr) {
      try {
        e.printStackTrace();
        tr.printStackTrace();
      } catch (Throwable e1) {
        log.fatal("could not write stacktrace of exception " + t.getName());
        addExceptionInfo(e1);
        addExceptionInfo(e);
        addExceptionInfo(tr);
      }
    }
  }

  private void addExceptionInfo(Throwable e) {
    log.fatal("exception info " + e.getMessage() + " " + e);
  }
}

它是这样使用的:

Thread.setDefaultUncaughtExceptionHandler(new CodeineUncaughtExceptionHandler());

由于某种原因,它似乎不起作用。从文档看来,这应该适用于所有线程。但是我的输出文件缺少异常的完整堆栈跟踪:

异常:线程“qtp18824904-18”中的 UncaughtExceptionHandler 抛出 java.lang.StackOverflowError

任何想法?

4

0 回答 0