Throwable errors

A Throwable error is an execution event which disrupts the normal flow of instructions. When a Throwable error is thrown, be that by the engine or manually, it will unwind the call stack until it is caught by a catch block or the global scope is reached, in which case the program is terminated with a fatal error. All finally blocks it encounters along the way will be executed.

To throw a Throwable error from within PHP code, one must use the throw keyword followed by an instance of the Error or Exception class or a subclass of one of them. Trying to throw an object that is not will result in an Error being thrown with the following message: Cannot throw objects that do not implement Throwable.

Подсказка

The Standard PHP Library (SPL) provides various built-in exceptions. And it's possible to create custom exceptions by extending the Exception class.

It is possible to handle a Throwable error within PHP by surrounding the code susceptible to throw an error in a try block. A try block must have at least one corresponding catch or finally block.

Замечание:

It is not recommended to catch Error objects as those signal a programming error.

Внимание

Throwable objects cannot be cloned. Attempting to clone such an object throws an Error, even if a subclass declares its own __clone() method, with the following message: Trying to clone an uncloneable object of class Exception.

Global exception handler

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.

Extending Exceptions

A user-defined exception can be defined by extending the built-in Exception class. To see which methods and properties are accessible within a child class derived from Exception visit its page.

If a class extends the built-in Exception class and re-defines 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 a 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
+Добавить

Примечания пользователей

Пользователи ещё не добавляли примечания для страницы
To Top