java 获取异常对象的错误号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11094396/
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
Getting error number of an exception object
提问by Chan
I have a program developed and it has a single entry point. A Try catch block is surrounding it.
我开发了一个程序,它有一个入口点。一个 Try catch 块围绕着它。
try {
Runner runner = new Runner();
// Adhoc code
UIManager.setLookAndFeel(new NimbusLookAndFeel());
runner.setupVariables();
runner.setLookAndFeel();
runner.startSessionFactory();
runner.setupApplicationVariables();
runner.setupDirectories();
// This will be used to test out frames in development mode
if (Runner.isProduction == true) {
execute();
} else {
test();
}
} catch (Exception e) {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
Logger.getRootLogger().error(e);
e.printStackTrace();
}
But suppose a null pointer exception is thrown, the message box is empty since the Exception doesn't contain a message. For this I added a logic-
但是假设抛出空指针异常,消息框是空的,因为异常不包含消息。为此,我添加了一个逻辑-
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at ");
}else{
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
This works all fine but I also want the line number to be displayed. How can I get it done. How can I get the line number of the exception?
这一切正常,但我也希望显示行号。我怎样才能完成它。如何获取异常的行号?
回答by james_bond
回答by DJ.
The metadata for the exception is stored in StackTraceElementclass, which you can get from your exception by calling getStackTrace().
异常的元数据存储在StackTraceElement类中,您可以通过调用getStackTrace()从异常中获取该类。
Example of using it is:
使用它的例子是:
if (e instanceof NullPointerException) {
NullPointerException n = (NullPointerException) e;
StackTraceElement stackTrace = n.getStackTrace()[0];
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}
回答by iracigt
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at line" + e.getStackTrace()[0].getLineNumber());
} else {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
Wow I was ninja'd by those above...
哇,我被上面的人忍了……
EDIT: Forgot to indent
编辑:忘记缩进