Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception vs Logging

Is the following way to code good practice?

try {     //my code here } catch (Exception e) {     logger.error("Some error ", e);     throw new MyCustomException("Some error ", e); } 

Moreover, should I..

  • use only the logger?
  • throw only the exception?
  • do both?

I understand that with throw I can catch the exception in another part of the callstack, but maybe additional logging has some hidden benefits and is useful as well.

like image 435
xrabbit Avatar asked Feb 27 '14 15:02

xrabbit


People also ask

Should I log before throwing exception?

Log it when you handle it So, better only log the exception when you handle it. Like in the following code snippet. The doSomething method throws the exception. The doMore method just specifies it because the developer doesn't have enough information to handle it.

What is exception logging?

The exception log is a rolling collection of 4 files; when a file is full, data is added to the next file. When the last file has been filled, data starts to be added to the first file, overwriting the previous data there. This cycle of writing continues, ensuring that the newest data is retained.

What is exception handling and logging?

Published: 13 Apr 2022. Logging and exception handling are like two peas in a pod. When a problem happens in your Java code, that typically means you have an exception that needs to be handled, and of course, any time an error or unanticipated event occurs, that occurrence should be logged appropriately.

Does Logger error stop execution?

With respect to logging vs. throwing, they're two separate concerns. Throwing an exception will interrupt your execution, prevent any further work, perhaps rollback database commits etc. Logging will simply dump info to the log file (or elsewhere).


1 Answers

Normally, I'd argue that you should either log or rethrow. Doing both will just cause every layer to log the exception again and again, which makes the logs hard to read. Even worse, it's hard to figure out how many errors you actually have - was it seven errors, or seven layers of the app which logged the same error?

This means that if you suppress an exception, you log it and say why you didn't think it was worth rethrowing.

On the other hand, if you re-throw the exception, you know it's either going to be caught and suppressed (in which case the catcher logs the exception and why it was suppressed), or it will bubble up out of your app and be caught by the app container, which will catch and log the exception. Every exception shows up once and only once in the logs.

like image 137
gustafc Avatar answered Oct 05 '22 20:10

gustafc