throw

(PHP 5, PHP 7, PHP 8)

The throw keyword is an expression and may be used in any expression context. It takes a Throwable object as an argument.

ЗастСрСТСння

Prior to PHP 8.0.0, the throw keyword was a statement and not an expression.

Attempting to throw a non-Throwable object will throw an Error. As user classes cannot implement Throwable directly, the thrown object must be an instance of Error or Exception, or of a subclass of one of them.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #1 Throwing a non-Throwable object

<?php
throw new class {};

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

PHP Fatal error:  Uncaught Error: Cannot throw objects that do not implement Throwable in Command line code:1
Stack trace:
#0 {main}

After using throw, the normal flow of execution is halted and the call stack is unwound until the object is caught by a catch block or the global scope is reached. All finally blocks encountered along the way are executed. If the global scope is reached, the object is passed to the exception handler set with set_exception_handler(), if one is set, and the script terminates once the handler returns. Otherwise, the program is terminated with a fatal error containing the stack trace indicating where the Throwable object was thrown.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #2 Throwing an Exception in the global scope

<?php
echo "Before exception\n";
throw new Exception('Stop execution');
echo "After exception\n";

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

Before exception
PHP Fatal error:  Uncaught Exception: Stop execution in Command line code:2
Stack trace:
#0 {main}
  thrown in Command line code on line 2

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #3 Throwing an Exception in a function

<?php

function foo() {
    echo "Before exception\n";
    throw new Exception('Stop execution');
    echo "After exception\n";
}

foo();

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ Ρ‰ΠΎΡΡŒ схоТС Π½Π°:

Before exception
PHP Fatal error:  Uncaught Exception: Stop execution in Command line code:3
Stack trace:
#0 Command line code(7): foo()
#1 {main}
  thrown in Command line code on line 3

As throw is an expression, it can be used to branch out on the result of another expression if its value is inappropriate.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #4 Using throw as an expression

Only permitted as of PHP 8.0.0.

<?php

function test() {
    do_something_risky() or throw new Exception('It did not work');
}

function do_something_risky() {
    return false; // Simulate failure
}

try {
    test();
} catch (Exception $e) {
    print $e->getMessage();
}

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

It did not work

It is possible to handle a thrown Throwable by using a try-catch block. See the error handling section for more information.

οΌ‹add a note

User Contributed Notes

There are no user contributed notes for this page.