2

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why [2]? Thanks agent 007!
1

The metadata for the exception is stored in StackTraceElement class, which you can get from your exception by calling 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());
}

Comments

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

Wow I was ninja'd by those above...

EDIT: Forgot to indent

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.