how can I get the exception name without getting the stack trace?
I am using exception.toString()
to convert the thrown exception into a string, but I only want the exception name likeNullPointerException
and not the entire stack trace.
How can I solve this?
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
To get it programmatically you can use: String exceptionClassName = e. getClass(). getName();
The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.
A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.
exception.getClass().getSimpleName();
Class#getSimpleName()
NOTE: this will not work in case if your exception is an anonymous class (although I have personally never seen an anonymous exception in any production code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With