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?
@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.