Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always catch an Exception, wrap it and pass it on up?

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!

like image 329
chance Avatar asked Feb 08 '11 10:02

chance


2 Answers

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).

like image 90
Tomasz Nurkiewicz Avatar answered Oct 09 '22 13:10

Tomasz Nurkiewicz


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.

like image 23
Manrico Corazzi Avatar answered Oct 09 '22 12:10

Manrico Corazzi