PHPのお勉強!

PHP TOP

Generator::throw

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

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

説明

public 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

add a note

User Contributed Notes 2 notes

up
1
gt199899 at gmail dot com
6 years ago
$gen = (function () {
try {
yield 1;
} catch (Exception $e) {
echo $e->getMessage();
}
})();

$gen->throw(new Exception('gen throw exception'));
up
-4
gt199899 at gmail dot com
6 years ago
$gen = (function () {
try {
yield 1;
} catch (Exception $e) {
echo $e->getMessage();
}
})();

$gen->throw(new Exception('gen throw exception'));
To Top