throw

(No version information available, might only be in Git)

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

Caution

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

Attempting to throw a non-Throwable object will throw an Error.

Example #1 Throwing a non-Throwable object

<?php
throw new class {};

The above example will output something similar to:

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. In the latter case, the program is terminated with a fatal error containing the stack trace indicating where the Throwable object has been thrown.

Example #2 Throwing an Exception in the global scope

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

The above example will output something similar to:

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

Example #3 Throwing an Exception in a function

<?php

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

foo();

The above example will output something similar to:

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.

Example #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();
}

The above example will output:

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.
To Top