Generator::throw

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::throw向生成器中抛入一个异常

说明

public Generator::throw(Throwable $exception): mixed

抛出一个异常到生成器并恢复生成器的执行。 与当前 yield 表达式被 throw $exception 语句替换是一样的行为。

如果调用此方法时生成器已经关闭,则将会在调用者的上下文中抛出异常。

参数

exception

抛出异常到生成器。

返回值

返回生成的值。

范例

示例 #1 抛出异常到生成器

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

以上例程会输出:

Foo
Exception: Test
Bar

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top