Exception Handling – When to Catch Exceptions

design-patternsexceptionsobject-oriented-design

MethodA calls an MethodB which in turn calls MethodC.

There is NO exception handling in MethodB or MethodC. But there is exception handling in MethodA.

In MethodC an exception occurs.

Now, that exception is bubbling up to MethodA, which handles it appropriately.

What is wrong with this?

In my mind, at some point a caller will execute MethodB or MethodC, and when exceptions do occur in those methods, what will be gained from handling exceptions inside those methods, which essentially is just a try/catch/finally block instead of just let them bubble up to the callee?

The statement or consensus around exception handling is to throw when execution cannot continue due to just that – an exception. I get that. But why not catch the exception further up the chain instead of having try/catch blocks all the way down.

I understand it when you need to free up resources. That's a different matter entirely.

Best Answer

As a general principle, don't catch exceptions unless you know what to do with them. If MethodC throws an exception, but MethodB has no useful way to handle it, then it should allow the exception to propagate up to MethodA.

The only reasons why a method should have a catch and rethrow mechanism are:

  • You want to convert one exception to a different one that is more meaningful to the caller above.
  • You want to add extra information to the exception.
  • You need a catch clause to clean up resources that would be leaked without one.

Otherwise, catching exceptions at the wrong level tends to result in code that silently fails without providing any useful feedback to the calling code (and ultimately the user of the software). The alternative of catching an exception and then immediately rethrowing it is pointless.