Skip to content

Instantly share code, notes, and snippets.

@crabmusket
Last active May 9, 2019 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crabmusket/28692b655db989a15ff35274451fdc62 to your computer and use it in GitHub Desktop.
Save crabmusket/28692b655db989a15ff35274451fdc62 to your computer and use it in GitHub Desktop.
PHP throwables example

PHP exceptions and errors

In PHP, Exceptions can be caught:

try {
    throw new \DomainException('input out of bounds');
} catch (\Exception $e) {
    echo "got exception\n";
} finally {
    echo "finally\n";
}
got exception
finally

The code above prints both messages and doesn't let the exception propagate.

However, if we make a more serious mistake like dereferencing null, an exception is not thrown. A more serious thing called an Error is thrown. Error is not a subclass of Exception so catching it has no effect:

try {
    $x = null;
    $x->frob();
} catch (\Exception $e) {
    echo "got exception\n";
} finally {
    echo "finally\n";
}
finally
PHP Error:  Call to a member function frob() on null in Psy Shell code on line 3

The "exception" still propagated, though the finally handler was still run before doing that.

If you really want to catch everything that can go wrong, you need to catch Throwable, which is a superclass of both Exception and Error:

try {
    $x = null;
    $x->frob();
} catch (\Throwable $e) {
    echo "got exception\n";
} finally {
    echo "finally\n";
}
got exception
finally

Both handlers ran and no exception was propagated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment