why is my UncaughtExceptionHandler not catching StackOverflowError?

513 Views Asked by At

I am running a Java daemon and want to catch unhandled exceptions. So I wrote a class:

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);
  }
}

and it is used like this:

Thread.setDefaultUncaughtExceptionHandler(new CodeineUncaughtExceptionHandler());

For some reason it seems not to work. From the documentation it looks this should be applied to all threads. However my output file is missing the full stacktrace of the exception:

Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "qtp18824904-18"

Any Idea?

0

There are 0 best solutions below