Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/32840399/printing-exception-vs-exception-getmessage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...