Throwable errors

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().

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.

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
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ

ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΠΈ Π΅Ρ‰Ρ‘ Π½Π΅ добавляли примСчания для страницы