Generator::throw
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Generator::throw — Throw an exception into the generator
Description
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
Example #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'));
?>
The above example will output: