Suppose I have a function a
that throws an exception $e
. Hence, according to phpdoc
I should have an annotation @throws
over the definition of a
.
When I have another function b
calling a
function b() {
a();
}
is it good practice/bad practice/correct/wrong to have a @throw
annotation over the definition of b
indicating that b
could throw that kind of exception?
Exception can be handled in any method in call stack either in main() method, p() method, n() method or m() method. Note : By default, Unchecked Exceptions are forwarded in calling chain (propagated).
unchecked exceptions are automatically propagated in java.
Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method.
An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b() , which calls c() , which calls d() , and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.
@throws
annotation is to indicate for the developer if the function() can throw an exception
First, you have to ask the question : why don't catch the exception in b()
method, is there a valid reason for that ?
Yes ? so you must add @throws
annotation, it will indicate you, or others developers that using function() b()
IS NOT SAFE and they will decide if they will
catch or propagate the exception
Also, since PHP doesn't force you to catch an exception thrown by another function, the @throws
annotation became a must/mandatory practice
As a matter of fact, b()
throws exceptions. Whether that happens directly or indirectly is irrelevant to the caller. Now, the annotations are not supposed to document internal implementation details that may change or even vary with different derived classes. Rather, the annotations document the visible behaviour for the caller, so the effective exceptions should also be part of the annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With