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)