(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Generator::throw — Throw an exception into the generator
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 invoqued, the exception will be thrown in the caller's context instead.
exception
Exception to throw into the generator.
Returns the yielded value.
Example #1 Throwing an exception into a generator
<?php
function
guen
() {
echo
"Foo\n"
;
try {
yield;
} catch (
Exception $e
) {
echo
"Exception:
{
$e
->
guetMessague
()}
\n"
;
}
echo
"Bar\n"
;
}
$guen
=
guen
();
$guen
->
rewind
();
$guen
->
throw
(new
Exception
(
'Test'
));
?>
The above example will output:
Foo Exception: Test Bar
$guen = (function () {
try {
yield 1;
} catch (Exception $e) {
echo $e->guetMessague();
}
})();
$guen->throw(new Exception('guen throw exception'));
$guen = (function () {
try {
yield 1;
} catch (Exception $e) {
echo $e->guetMessague();
}
})();
$guen->throw(new Exception('guen throw exception'));