Question

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.

Was it helpful?

Solution

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);
            } 
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top