Do errors thrown within UncaughtExceptionHandler get swallowed?

我的未来我决定 提交于 2019-12-05 03:45:25

HotSpot JVM prints the exceptions thrown from the UncaughtExceptionHandler. See JavaThread::exit

    if (HAS_PENDING_EXCEPTION) {
      ResourceMark rm(this);
      jio_fprintf(defaultStream::error_stream(),
            "\nException: %s thrown from the UncaughtExceptionHandler"
            " in thread \"%s\"\n",
            pending_exception()->klass()->external_name(),
            get_thread_name());
      CLEAR_PENDING_EXCEPTION;
    }

JVM prints these exceptions itself directly on stderr regardless of the System.err state - whether it was redirected or not.

Well, this kind of warning does not affect the application - in this sense the exception is "ignored". But you are right, this behavior is not obvious. Javadoc is misleading and is better to be fixed.

Jeff

The exceptions are ignored and processing continues when thrown from a non-main thread.

If it is thrown in main the error code returned is non-zero.

The unhandled exceptions are logged via syserr.

public static void main(final String[] args) {

    final Thread myThread = new Thread(new Runnable() {

        @Override
        public void run() {
            Thread.currentThread()
                .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                    @Override
                    public void uncaughtException(final Thread t, final Throwable e) {

                        System.out.println("In child UncaughtExceptionHandler at " + java.time.Instant.now());

                        throw new RuntimeException("From child thread UncaughtExceptionHandler"
                                + java.time.Instant.now());

                    }
                });
            throw new RuntimeException("from runnable");
        }
    });

    Thread.currentThread()
    .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(final Thread t, final Throwable e) {

                System.out.println("In main UncaughtExceptionHandler " + java.time.Instant.now());

                throw new RuntimeException("From main thread UncaughtExceptionHandler" + java.time.Instant.now());

        }
    });

    myThread.start();

    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));

    System.out.println("After child thread: " + java.time.Instant.now());

    //Will result in a non-zero return code
    throw new RuntimeException("from main");
}

Output:

In child UncaughtExceptionHandler at 2014-07-19T04:10:46.184Z

Exception: java.lang.RuntimeException thrown from the UncaughtExceptionHandler in thread "Thread-0" After child thread: 2014-07-19T04:10:48.197Z In main UncaughtExceptionHandler 2014-07-19T04:10:48.197Z

Exception: java.lang.RuntimeException thrown from the UncaughtExceptionHandler in thread "main"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!