In PHP, Exception
s 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.