Java only get Exception name without StackTrace

Broadwell picture Broadwell · Mar 20, 2015 · Viewed 20.7k times · Source

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?

Answer

Sergey Pauk picture Sergey Pauk · Mar 20, 2015
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)