Chan
Chan

Reputation: 2641

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?

Upvotes: 2

Views: 13157

Answers (3)

iracigt
iracigt

Reputation: 282

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

Upvotes: 1

james_bond
james_bond

Reputation: 6906

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.

Upvotes: 5

DJ.
DJ.

Reputation: 6784

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

Upvotes: 1

Related Questions