2

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

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

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

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

4

3 回答 3

5

在这个问题的答案中,您可以使用以下代码段:

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

尽管建议使用日志库,例如log4j

于 2012-06-19T04:39:36.763 回答
1

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

使用它的例子是:

if (e instanceof NullPointerException) {
    NullPointerException n = (NullPointerException) e;
    StackTraceElement stackTrace = n.getStackTrace()[0];
    SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}
于 2012-06-19T04:39:20.443 回答
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());
} 

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

编辑:忘记缩进

于 2012-06-19T04:41:01.210 回答