Best practices: Use of @throws in php-doc, and how it could be handle

Federkun picture Federkun · Mar 23, 2013 · Viewed 21.3k times · Source

Let's say I have a class with a method like this:

/*
 *
 * Loads the user from username.
 *
 * @param string $username The username
 *
 * @return UserInterface
 *
 * @throws userNotFoundException if the user is not found
 */
public function getUser($username)
{
    // someFunction return an UserInterface class if found, or null if not.
    $user = someFunction('SELECT ....', $username);
    if ($user === null) {
        throw new userNotFoundException();
    }

    return $user
}

Now let's say that someFunction could throw a InvalidArgumentException / RuntimeException / PDOException for XYZ reasons. What should I do? And what not?

Number 1

Add all the possible exceptions that could throw someFunction in php-docs.

/*
 *
 * Loads the user from username.
 *
 * @param string $username The username
 *
 * @return UserInterface
 *
 * @throws userNotFoundException if the user is not found
 * @throws InvalidArgumentException
 * @throws ...
 */

Number 2

Add a try-catch block to ensure that the method should throw exceptions ONLY documented

/*
 *
 * Loads the user from username.
 *
 * @param string $username The username
 *
 * @return UserInterface
 *
 * @throws userNotFoundException if the user is not found
 * @throws RuntimeException 
 */
public function getUser($username)
{
    try {
        $user = someFunction('SELECT ....', $username);
    } catch (Exception $e) {
        throw new RuntimeException();
    }

    if ($user === null) {
        throw new userNotFoundException();
    }

    return $user
}

Number 3

Don't do anything.

Answer

Jani Hartikainen picture Jani Hartikainen · Mar 23, 2013

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.