Skip to content
Advertisement

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.

Advertisement

Answer

I use both in some cases, logging and throwing the exception. Especially, it’s useful in APIs. By throwing the exception, we allow the caller to handle it, and by logging, we can identify the root cause of it ourselves.

And, if the caller is in the same system, then if we add logs in every catch, there will be duplicate logs.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement