Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility methods and Exceptions [closed]

Tags:

java

exception

Is it always good to throw exceptions from Utility methods to the caller instead of catching them using try | catch blocks? I know it debatable, but just wanted to get input from different views!

like image 755
jagamot Avatar asked Mar 20 '26 20:03

jagamot


1 Answers

I am not sure what you mean by utility methods, but the rules (or rather, guidelines) apply the same to almost all cases.

General rule of thumb (and I nearly quote it from Effective Java 2nd edition):

  1. Use exceptions only for exceptional conditions
  2. Throw exceptions appropriate for the abstraction level

Each higher level should catch exceptions from lower levels (and perhaps envelop and re-throw) and throw exceptions that can be understood at a higher level. That means (among other things) - the layer you are throwing the exception from should be sure that its thrown exception can be interpreted at a higher level and taken care of.


I like to think about it that way - if you throw an exception from a method you should be sure that:

  1. You don't know or don't want to take care of it (by some fail-over mechanism) at the iniating method
  2. Higher levels know what to do with it.
  3. Client (if it's propagated all the way to the client) will get some useful information out of it

There is much much more, but then again - the book I linked to should be a great place to read up on (Java in general too).

like image 186
ZenMaster Avatar answered Mar 22 '26 08:03

ZenMaster