PHP 8.4.1 Released!

Generator::throw

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

Generator::throwThrow an exception into the generator

Descrizione

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

Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current yield expression was replaced with a throw $exception statement.

If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead.

Elenco dei parametri

exception

Exception to throw into the generator.

Valori restituiti

Returns the yielded value.

Esempi

Example #1 Throwing an exception into a generator

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

Il precedente esempio visualizzerà:

Foo
Exception: Test
Bar

add a note

User Contributed Notes 2 notes

up
1
gt199899 at gmail dot com
7 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
7 years ago
$gen = (function () {
try {
yield 1;
} catch (Exception $e) {
echo $e->getMessage();
}
})();

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