I've read such a method:
public void doSomething throws MyException{
...
try {
doSomthingElse();
} catch (MyException e){
log.errer(e.getMessage());
throw new MyException(e.getMessage(),e);
}
...
}
But I prefer to:
public void doSomething throws MyException{
...
doSomthingElse();
...
}
Anyone knows any reason for the first method? There is only one type of Exception, and it is not handled in this method, is there any reason to catch it, wrap it without new information, and then pass it on up?Why not just write it in the second way? Thanks!
Logging exception and throwing it further is actually an anti-pattern for several reasons. The rule of thumb is: if you can't do anything useful to handle the exception (logging is not handling the exception in most cases), let your framework/container do it for you. If you can (for instance use different storage when database is not available, queue packages when network is down), log the exception and proceed (always remember to log stack as well).
If you have a checked exception, wrap it in runtime one and rethrow (create your custom exception or look for existing one that match your needs).
It depends on the relationship between the classes. In general I prefer to delegate logging to the caller. Usually is the caller who knows how to handle an exception, too: retry? notify the user? log? forget?
Misko Hevery is a good read on the subject, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With