在PHP中考虑这个简单的生成器函数。
function createAGenerator() {
echo 'Before First Yield',"\n";
yield 'First Yield';
echo 'Before Second Yield',"\n";
yield 'Second Yield';
echo 'Before Third Yield',"\n";
yield 'Third Yield';
}
如果我用生成器对象的
throw
方法
$generator = createAGenerator();
try {
$generator->throw(new Exception('Throwing into a Generator'));
} catch(Exception $e) {
echo 'Caught Exception: ', $e->getMessage(), "\n";
}
echo 'Resuming Main Program Execution',"\n";
生成器函数将重新抛出异常以供我捕获。这一切都如我所料。
然而,我的发电机现在似乎永远卡住了。如果我想继续
next
屈服,或
send
如果在中有一个新值,则生成器似乎刚刚返回
NULL
.例如,以下程序
<?php
function createAGenerator() {
echo 'Before First Yield',"\n";
yield 'First Yield';
echo 'Before Second Yield',"\n";
yield 'Second Yield';
echo 'Before Third Yield',"\n";
yield 'Third Yield';
}
$generator = createAGenerator();
try {
$generator->throw(new Exception('Throwing into a Generator'));
} catch(Exception $e) {
echo 'Caught Exception: ', $e->getMessage(), "\n";
}
echo 'Resuming Main Program Execution',"\n";
var_dump($generator->send('Some Value'));
var_dump($generator->current());
var_dump($generator->next());
var_dump($generator->current());
返回以下输出。
Before First Yield
Caught Exception: Throwing into a Generator
Resuming Main Program Execution
NULL
NULL
NULL
NULL
发电机有办法从中恢复吗?或者,生成器中的未捕获异常是否会“破坏”该生成器的当前实例?