PHP 8.3.4 Released!

Generator::throw

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

Generator::throwLance une exception dans le générateur

Description

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

Lance une exception dans le générateur et reprend son exécution. Le comportement sera le même que si l'expression yield courante ait été remplacée avec une expression throw $exception.

Si le générateur est déjà fermé quand cette méthode est appelée, l'exception sera levée dans le contexte de l'appelant à la place.

Liste de paramètres

exception

Exception à lancer dans le générateur.

Valeurs de retour

Retourne la valeur cédée.

Exemples

Exemple #1 >Lance une exception dans un générateur

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

L'exemple ci-dessus va afficher :

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