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开发者_如何学Go 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.
The reason for this "wrapper" in your example might be not ever miss an exception and at least log it. I see no other sense in that catch
block, as those are usually declared to recover from an exception and maybe do "proper cleanup".
I prefer inheriting a custom exception class from an existing exception.
In that new exception's constructor, the logging takes place. That way, I'll save the overhead of generating another new Exception with full trace, and the other overhead going with it.
Other than wanting to log the exception or do something else with it "locally", i don't see any reason.
You might want to catch and log the specific error where it occurs as for better logging, but then handle it on a higher level by throwing a new Exception.
精彩评论