PHP.nl

Generator::throw

Generator::throw

Throw an exception into the generator

mixed **Generator::throw** Throwable $exception

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 statement. throw $exception

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

exceptionException to throw into the generator.

Returns the yielded value.

Voorbeeld: Throwing an exception into a generator

<?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'));
?>
Foo
Exception: Test
Bar

Documentatie