« Generator::send
Generator::valid »

Generator::throw

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

Generator::throw — 例外をジェネレータにスローする

説明

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

例外をジェネレータにスローして、ジェネレータを続行します。 この振る舞いは、現在の yield 式の部分を throw $exception 文に置き換えたのと同じになります。

このメソッドの起動時に既にジェネレータが閉じられている場合は、呼び出し側のコンテキストに例外がスローされます。

パラメータ

exception

ジェネレータにスローする例外。

戻り値

yield した値を返します。

例

例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

関連キーワード:
ジェネレータ   Generator   throw   スロー   Exception   exception   yield   send   valid   Throwable   mixed   続行   起動   コンテキスト   catch   getMessage   rewind
関連する関数・ページ:
class.generator   generator.send   generator.next   generator.getreturn   language.generators   generator.rewind