문제

Small example:

 public class App {   
     public static void main(String[] args) {
         throw new RuntimeException("Test exception");
     }
 }

Prints following as expected:

Exception in thread "main" java.lang.RuntimeException: Test exception
    at App.main(App.java:5)

Lets modify this program:

public class App {    
    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                if (e instanceof RuntimeException) throw (RuntimeException)e;
            }
        });
        throw new RuntimeException("Test exception");
    }
}

Prints:

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

Question:

Why message doesn't contain any information about where it occurs and there is no stack trace, message?

As for me exception message looks weird.

도움이 되었습니까?

해결책

The Java API documentation says:

void uncaughtException(Thread t, Throwable e)

Method invoked when the given thread terminates due to the given uncaught exception. Any exception thrown by this method will be ignored by the Java Virtual Machine.

So if you want the program to terminate on some exceptions and print their message/stacktrace you should do:

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof RuntimeException) {
                 e.printStackTrace();
                 System.exit(1);
            } 
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top