获取异常对象的错误号

时间:2012-06-19 04:32:03

标签: java exception nullpointerexception

我开发了一个程序,它有一个入口点。一个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();
        }

但是假设抛出空指针异常,消息框为空,因为Exception不包含消息。为此,我添加了一个逻辑 -

 if(e instanceof NullPointerException){
        NullPointerException n =(NullPointerException) e;
        SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at ");
    }else{
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}

这一切都很好,但我也希望显示行号。我怎样才能完成它。如何获取异常的行号?

3 个答案:

答案 0 :(得分:5)

在此question的答案中,您可以使用以下代码段:

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

建议使用log4j等日志库。

答案 1 :(得分:1)

异常的元数据存储在StackTraceElement类中,您可以通过调用getStackTrace()从异常中获取。

使用它的例子是:

if (e instanceof NullPointerException) {
    NullPointerException n = (NullPointerException) e;
    StackTraceElement stackTrace = n.getStackTrace()[0];
    SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}

答案 2 :(得分:1)

if(e instanceof NullPointerException){
    NullPointerException n =(NullPointerException) e;
    SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at line" + e.getStackTrace()[0].getLineNumber());
} else {
    SwingHelper.showErrorMessageMainFrame(e.getMessage());
} 

哇,我被上面的人忍住了......

编辑:忘记缩进