2

I want to make logging during my java application development. I want the information from the exception object during exception handling. Which information inquiry from the object is preferred? Using the .getMessage() method, or the .toString() method?

My .getMessage() code snippet:

try { //my code } catch( Exception ex ) { log.log( Level.SEVERE, ex.getMessage(), ex ); } 

My .toString() code snippet:

try { //my code } catch( Exception ex ) { log.log( Level.SEVERE, ex.toString(), ex ); } 
1
  • Well, which one has proved more useful to you when you tried it? Commented Dec 21, 2013 at 20:07

1 Answer 1

1

By default, an exception toString() method will put together the name of the exception class and the message of the exception. Therefore, the only difference with getMessage is that toString() will give you also the class of the exception.

Now, either way, java.util.logging will prints the name of the class, its message and the stacktrace anyway because you pass the exception as the third argument of the call to log. Therefore, it is useless to provide the result of getMessage() or toString(). You should instead put a message indicating the context in which the exception happened, and other relevant information.

For example, consider the following:

 String identifier = "duck"; try { int result = Integer.parseInt(identifier); } catch(Exception e) { log.log(Level.SEVERE, "Failed to parse the identifier.", e); } 

Since "duck" is not an integer, this will result in an exception. The program will then print:

SEVERE: Failed to parse the identifier. java.lang.NumberFormatException: For input string: "duck" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at test.DDD.main(DDD.java:13) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.