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.
try-catch
block at all.Result<T>
type (a type that either stores a result of a computation, or an error), and return it from your otherwise throwing functions. Propagating an error up the stack would entail reading every return value, checking if its an error, and returning an error if so.catch
or adding athrows
statement. If the point of the exceptions is to allow them to be ignored in the middle layers between the thrower and the catcher, then forcing those layers to acknowledge them is counter productive since athrows
clause is the same as having a catch-and-re throw every time, it still forces you to change all layers if, for example, the exception thrown/caught is changed.