DEV Community

Eelco Verbrugge
Eelco Verbrugge

Posted on • Updated on

PHP Errors vs. Exceptions

What are the differences between Errors and Exceptions?

Error

When an operation fails, does not succeed.

Exception

When an alternative or exceptional route appears.

Example

If a delivery guy tries to deliver my package but he failed to do so, that's an Error.

But if he got attacked by my dog, that's an Exception.

If the he got attacked by my dog, I throw an Exception that my dog attacked him.

If the package has not been delivered, you don't throw an Exception. You return false or return an error message "Package could not be delivered".

try {
    DeliverPackage();
}
catch (Exception $e) {
    return "Could not deliver the package because my dog attacked him";
}
return false;
Enter fullscreen mode Exit fullscreen mode

Thats all folks~

Top comments (1)

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