A Throwable error is an execution event which disrupts
the normal flow of instructions. When a Throwable error
is thrown, it will unwind the call stack
until it is caught by a catch block or the global scope is reached.
All finally blocks it encounters along the way will be executed.
An uncaught Throwable error is passed to the
exception handler set with set_exception_handler(),
if one is set; otherwise, the program is terminated with a fatal error.
To throw a Throwable error from within PHP code,
use the throw keyword.
The Standard PHP Library (SPL) provides various built-in exceptions. It is also possible to create custom exceptions by extending the Exception class.
It is possible to handle a Throwable error within PHP
by surrounding the code that may throw an error in a try block.
Throwable objects cannot be cloned.
Attempting to clone such an
object throws an Error with the following message:
Trying to clone an uncloneable object of class ClassName.
This happens even if a subclass declares its own
__clone() method.
See Exception::__clone() and
Error::__clone().
It's possible to add a handler for any uncaught
Throwable with
set_exception_handler().
This is similar to wrapping the entire code in a try-catch block,
except that execution does not resume afterwards: the script
terminates once the handler returns.
A user-defined exception can be defined by extending the built-in Exception class.
If a class extends the built-in Exception class and
redefines the constructor,
it is highly recommended that it also call parent::__construct()
to ensure all available data has been properly assigned.
The __toString() method can be overridden
to provide custom output when the object is used as a string.
示例 #1 Extending Exception
<?php
class CustomException extends Exception
{
// Redefine the constructor so message isn't optional
public function __construct($message, $code = 0, ?Throwable $previous = null) {
// some code
// Ensure everything is assigned properly
parent::__construct($message, $code, $previous);
}
// Custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
try {
throw new CustomException("Something happened", 5);
} catch (CustomException $e) {
echo "Caught custom exception\n", $e;
$e->customFunction();
}以上示例会输出:
Caught custom exception CustomException: [5]: Something happened A custom function for this type of exception
The Exception class has many subclasses, among them the SPL exceptions and those defined by extensions.