Frage

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 );
}
War es hilfreich?

Lösung

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top