DesirePRG DesirePRG - 6 months ago 41
Java Question

Printing Exception vs Exception.getMessage

Is there a best practice on using the followng two pieces of code regarding exceptions.

//code1

} catch (SomeException e) {
logger.error("Noinstance available!", e.getMessage());
}

//code2
} catch (SomeException e) {
logger.error("Noinstance available!", e);
}


When should I use the getMessage method of an exception?

Answer

The first doesn't compile because the method error accept a String as first parameter and a Throwable as second parameter.

e.getMessage() is not a Throwable.

The code should be

} catch (SomeException e) {
    // No stack trace
    logger.error("Noinstance available! " + e.getMessage());
}

Compared with

} catch (SomeException e) {
    // Prints message and stack trace
    logger.error("Noinstance available!", e);
}

The first prints only a message. The second prints also the whole stack trace.

It depends from the context if it is necessary to print the stack trace or not.

If you already know why an exception can be thrown it is not a good idea to print the whole stack trace.

If you don't know, it is better to print the whole strack trace to find easily the error.