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?

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
Chan
  • 2,601
  • 6
  • 28
  • 45

3 Answers3

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.

Community
  • 1
  • 1
james_bond
  • 6,778
  • 3
  • 28
  • 34
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());
}
DJ.
  • 6,664
  • 1
  • 33
  • 48
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

iracigt
  • 282
  • 1
  • 5