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

I read a method like this:

public void doSomething throws MyException{ ... try { doSomthingElse(); } catch (MyException e){ log.errer(e.getMessage()); throw new MyException(e.getMessage(),e); } ... } 

But I prefer:

 public void doSomething throws MyException{ ... doSomthingElse(); ... } 

Does anyone know the 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? Why not just write it in the second? Thanks!

+6
exception-handling
source share
5 answers

Excluding a journal and adding it is actually an anti-pattern for several reasons . Rule of thumb: if you cannot do anything useful to handle the exception (logging does not handle the exception in most cases), let your framework / container do it for you. If you can (for example, use another repository when the database is unavailable, queue packets if the network fails), write down the exception and continue (always remember to also write the stack).

If you have a checked exception, wrap it at runtime and reinstall (create your own exception or look at an existing one that suits your needs).

+5
source share

It depends on the relationship between the classes. In general, I prefer to delegate registration to the caller. Usually it is the caller who knows how to handle the exception too: try again? notify user? magazine? to forget?

Misko Hevery reads well on this subject.

+2
source share

The reason for this "wrapper" in your example might not be to miss the exception and at least register it. I do not see any other meaning in this catch , as they are usually declared for recovery from an exception and, possibly, perform the โ€œcorrect cleanupโ€.

I prefer to inherit my own exception class from an existing exception.

This new exception constructor is journaling. This way, I will save the overhead in order to generate another new Exception with a full trace, and other overhead comes with it.

+1
source share

Besides the fact that you want to register an exception or do something else with it โ€œlocallyโ€, I see no reason.

0
source share

You may want to catch and log a specific error where this happens, for better logging, but then handle it at a higher level, throwing a new exception.

0
source share

All Articles