I have a generator that passes a collection of values into a method and yields the result. The method that is called may return an exception. When this happens, I would like the exception to fall through to the code that calls the generator to handle the exception, and then continue looping the generator.
To illustrate this, the following is an example of generator that will yield 1
, throw an \Exception
, then yield 3
.
/** @var \Generator $gen */
$gen = function () {
for ($i = 1; $i <= 3; $i++) {
if ($i == 2) {
throw new \Exception('Exception thrown for 2');
}
yield $i;
}
};
This is an example of my attempt to run this code such that I can get it to yield 3
$g = $gen();
var_export($g->current());
echo "\n";
try {
$g->next();
var_export($g->current());
echo "\n";
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
try {
$g->next();
var_export($g->current());
echo "\n";
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
The following is the output of the above code.
1
Exception thrown for 2.
NULL
So a repeated calls to next()
does nothing and current()
will return NULL
, where I would like the generator to continue past the Exception so I can get 3
.