Issue
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 !
Solution
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 !
Answered By - Oussama ZAGHDOUD Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.