DEV Community

Discussion on: PHP Errors vs. Exceptions

Collapse
 
bdelespierre profile image
Benjamin Delespierre • Edited

Nice article.

I would like to quote my Java teacher here: exception are for exceptionnal cases. You want to use them when the piece of code you're writing cannot make a decision based on the current situation. Then you throw an exception to delegate that decision to the calling class and so on...

If the code can handle the situation at hand, for instance by returning a value indicating the error, then it should not throw an exception.

Here's an example:

function get_user(string $email)
{
    $stmt = get_connection()->prepare(
        "select * from users where email=:email"
    );

    // the DB is unreachable, 
    // we don't know what to do,
    // we bail!
    if (false === $stmt) {
        throw new \RuntimeException(
            "Unable to connect to DB"
        );
    }

    // the query execution failed,
    // it happens, 
    // we return false to indicate failure
    if (! $stmt->execute([':email' => $email]) {
        return false;
    }

    $user = $stmt->fetch();

    // no user found,
    // it happens,
    // we return null to indicate the user 
    // was not found
    if (is_null($user)) {
        return null;
    }

    // everything went fine,
    // we return the user!
    return new User($user);
}
Enter fullscreen mode Exit fullscreen mode