Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error handling

As I'm sure you all know Java enforces a very strict pattern for error handling whereby any exception must be handled through either a try catch block or by declaring a method with the throws keyword. (I might add I really like the way its done)

Having said that; what I am struggling with is deciding on what the correct approach is to handling errors in various methods. Coming from a C#/VB.NET background I have previously always strictly adhered to handling errors (In everything but the most specific circumstances) at the bottommost of the stack, however I am not convinced that this is the best approach in Java.

Could anyone provide any input regarding this? What is considered best practice? How does one decide if they should infact throw an exception outside the method or handle it internally (Obviously some cases are obvious but allot aren't)?

like image 689
Maxim Gershkovich Avatar asked Jul 15 '26 11:07

Maxim Gershkovich


2 Answers

On a per-method basis, I ask myself:

  1. Does this method have enough information to properly handle this exception? If yes, handle it. Otherwise...
  2. Does the caller have enough information to properly handle this exception? If yes, rethrow. Otherwise...
  3. Does the caller need to specifically handle failures in the operations from this component? If yes, rethrow as nested within a component exception subclass. Otherwise...
  4. Rethrow as unchecked.
like image 54
Brett Kail Avatar answered Jul 17 '26 23:07

Brett Kail


It's a trite answer, but catch the exception where you can actually do something with it to recover. Different exceptions will mean you may handle exceptions at different levels in the architecture.

like image 36
MeBigFatGuy Avatar answered Jul 18 '26 00:07

MeBigFatGuy