Generator::throw

(PHP 5 >= 5.5.0, PHP 7)

Generator::throwThrow an exception into the generator

Beschreibung

public 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.

Parameter-Liste

exception

Exception to throw into the generator.

Rückgabewerte

Returns the yielded value.

Changelog

Version Beschreibung
7.0.0 The exception parameter also accepts Throwable now.

Beispiele

Beispiel #1 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'));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Foo
Exception: Test
Bar