Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception annotations for propagated exceptions

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?

like image 386
marcosh Avatar asked Sep 28 '15 14:09

marcosh


People also ask

How do you handle exception propagation?

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).

What exceptions are automatically propagated?

unchecked exceptions are automatically propagated in java.

How are exceptions 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.

How does an exception propagates in the code?

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.


2 Answers

@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

like image 177
Halayem Anis Avatar answered Oct 21 '22 09:10

Halayem Anis


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.

like image 33
Ulrich Eckhardt Avatar answered Oct 21 '22 09:10

Ulrich Eckhardt