php8.5
Home/ Manual/ predefined / generator/ Generator::throw

Generator::throw

PHP function Edit on GitHub ✎

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Throw an exception into the generator

Description

Generator::throw(Throwable $exception): mixed

Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current Yield expression was replaced with a throw $exception statement.

If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead.

Parameters

exception

Exception to throw into the generator.

Return Values

Returns the yielded value.

Examples

Throwing an exception into a generator

php
<?php
function gen() {
    echo "Foo\n";
    try {
        yield;
    } catch (Exception $e) {
        echo "Exception: {$e->getMessage()}\n";
    }
    echo "Bar\n";
}
 
$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>

The above example will output:

output
Foo
Exception: Test
Bar

Source: language/predefined/generator/throw.xml · from the official PHP manual (php/doc-en)