2

プログラムを開発しましたが、エントリポイントは1つです。トライキャッチブロックがそれを囲んでいます。

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();
        }

ただし、nullポインター例外がスローされたとすると、例外にメッセージが含まれていないため、メッセージボックスは空になります。このために私はロジックを追加しました-

 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 に答える