Exceptions
Table of Contents
PHP has an exception model similar to that of other programming
languages. An exception can be throw
n, and caught ("catch
ed") within
PHP. Code may be surrounded in a try
block, to facilitate the catching
of potential exceptions. Each try
must have at least one corresponding
catch
or finally
block.
If an exception is thrown and its current function scope has no catch
block, the exception will "bubble up" the call stack to the calling
function until it finds a matching catch
block. All finally
blocks it encounters
along the way will be executed. If the call stack is unwound all the way to the
global scope without encountering a matching catch
block, the program will
terminate with a fatal error unless a global exception handler has been set.
The thrown object must be an instanceof
Throwable.
Trying to throw an object that is not will result in a PHP Fatal Error.
As of PHP 8.0.0, the throw
keyword is an expression and may be used in any expression
context. In prior versions it was a statement and was required to be on its own line.