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
Java only get Exception name without StackTrace
提问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 likeNullPointerException
and not the entire stack trace.
我正在使用exception.toString()
将抛出的异常转换为字符串,但我只想要异常名称,NullPointerException
而不是整个堆栈跟踪。
How can I solve this?
我该如何解决这个问题?
回答by Sergey Pauk
exception.getClass().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)
注意:如果您的异常是匿名类,这将不起作用(尽管我个人从未在任何生产代码中看到匿名异常)