Getting error number of an exception object
Solution 1
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.
Solution 2
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
Solution 3
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());
}
Chan
Shit just got real ~@dulitharw Java|Ruby|Python|Scala|Sinatra|Blogger
Updated on June 04, 2022Comments
-
Chan almost 2 years
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?
-
Ruchir Baronia over 8 yearsWhy
[2]
? Thanks agent 007!