Best practices: Use of @throws in php-doc, and how it could be handle
Personally I would consider treating @throws
similar to Java's checked exceptions
The way this works in Java is that basically exceptions that inherit from RuntimeException can be thrown and don't have to be handled. Any other types of exceptions must have a try-catch block to handle them. This handling code must be in the caller.
Basically in PHP kinda like this:
When a method has a @throws
annotation, you have to add code to handle its exceptions.
Any exceptions that don't get mentioned are optional for handling in the calling code.
Now, I don't 100% follow this principle myself. The whole handling exceptions thing is sort of up to the programmer's preference, but this is just some thoughts on how I think it could be handled in a reasonable fashion.
With regards to documentation, if a function explicitly throws an exception then it should be included in the function's documentation. Thus, for each throw
statement, there should be a corresponding @throws
in the PHP documentation.
With regards to handling, if there are some operations that should be executed when the exception is thrown then catch it. Otherwise, let it bubble up -- provided there is a catch
statement going to handle it later.
Update:
A few years later, I have changed to the opinion that one should only let an exception "bubble up" unmodified when the exception is still relevant to the module's level of abstraction. Catch and re-throw strategies should be employed to make the exception more meaningful. It should also make error handling more secure by avoiding unnecessary disclosure of information about modules underlying the abstraction.
/** * @throws UserNotFoundException */public function getUser($username){ try { $user = someFunction('SELECT ....', $username); } catch (DatabaseException $dbe) { /* Re-throw since a database exception may no longer be * meaningful to the caller. */ throw new UserNotFoundException(); } return $user}