Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java only get Exception name without StackTrace

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?

like image 606
Broadwell Avatar asked Mar 20 '15 18:03

Broadwell


People also ask

How do I get the exception name?

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.

How do you find the throwable exception name?

To get it programmatically you can use: String exceptionClassName = e. getClass(). getName();

Why we must call printStackTrace () in catch block?

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.

What is exception StackTrace?

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.


1 Answers

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)

like image 81
Sergey Pauk Avatar answered Oct 05 '22 22:10

Sergey Pauk