Home > Net >  How to stop printing the StackTrace of exceptions in the console
How to stop printing the StackTrace of exceptions in the console

Time:07-05

If an exception is thrown without catching it, the default behaviour is to print the exception stack trace in the console. How to do to change this behaviour for example to write something else in the console or do some tasks wihtout catching those excpetions.

The goal is to stop writing the stackTrace for all the Exceptions and do any other task , for example write "No output here !" if an Exception is thrown .

public class Tester {
    public static void main(String[] args) {
        throw new RuntimeException("my message");
    }
}

Output :

Exception in thread "main" java.lang.RuntimeException: my message
    at src.Tester.main(Tester.java:17)

Excpected Output:

No output here !

CodePudding user response:

From the Java documentaiton here : A thread can take full control of how it responds to uncaught exceptions by having its uncaught exception handler explicitly set. So you can simply call the setUncaughtExceptionHandler method of the current thread and create your own UncaughtExceptionHandler instance, passing this instance to the method as argument exactly like that :

import java.lang.Thread.UncaughtExceptionHandler;

public class Tester {
    public static void main(String[] args) {

        Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                // write here the new behaviour and it will be applied for all the uncaughted Exceptions
                System.out.println("No output here !");
            }
        });

        throw new RuntimeException("my message");
    }
}

Output :

No output here !

CodePudding user response:

A good way of programming is that you capsulate the critical code in a try-catch.

try {
    File.open();
} catch (Exception ex) {
    System.err.println("ErrorMessage: No Output here!");
}

The Exception catches everything, but you could always specify it for a RuntimeException. That's what works best for me and my code.

  • Related