CakeFest 2024: The Official CakePHP Conference

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 3 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'));
up
-6
jeudipolanco at ymail dot com
7 years ago
there have errors the form correct to do that is of this way:

function gen() {
echo "Foo\n";
try {

throw new Exception('Prueba');

} catch (Exception $e) {
echo "Excepción: {$e->getMessage()}\n";
}
echo "Bar\n";
}

gen();

i resolved one tecnic of how work getMessage look at it:

$myarray=array();

if($respuesta == "Mark"){

for($i=5;$i<=16;$i++){
try {

$palabra="soy la excepcion en la linea:".$i;

throw new Exception($palabra);

}
catch(Exception $e) {

$myarray[$e->getLine()] =$palabra;

if($e->getLine() == $i){
echo "<br><b>La excepción se creó en la línea : " .$e->getLine()."LA LINEA DICE:". $myarray[$e->getLine()]."</b>";
}//if

}//catch


}//for

}//if
To Top