简体   繁体   English

获取异常对象的错误号

[英]Getting error number of an exception object

I have a program developed and it has a single entry point. 我开发了一个程序,它只有一个入口点。 A Try catch block is surrounding it. 尝试捕获块围绕它。

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? 如何获得异常的行号?

Among the answer to this question , you can use this snippet: 在此问题的答案中,您可以使用以下代码段:

public static int getLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}

Althought is recommended to use a logging library such as log4j . 尽管建议使用日志库,例如log4j

The metadata for the exception is stored in StackTraceElement class, 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());
}
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 编辑:忘记缩进

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM