java Java只获取没有StackTrace的异常名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29173645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:47:51  来源:igfitidea点击:

Java only get Exception name without StackTrace

javastringexceptionstack-trace

提问by Broadwell

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 likeNullPointerExceptionand not the entire stack trace.

我正在使用exception.toString()将抛出的异常转换为字符串,但我只想要异常名称,NullPointerException而不是整个堆栈跟踪。

How can I solve this?

我该如何解决这个问题?

回答by Sergey Pauk

exception.getClass().getSimpleName();

Class#getSimpleName()

类#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)

注意:如果您的异常是匿名类,这将不起作用(尽管我个人从未在任何生产代码中看到匿名异常)