Generator::throw

Generator::throw

(PHP 5 >= 5.5.0, PHP 7)

Generator::throwThrow an exception into the generator

Description

public mixed Generator::throw ( Throwable $exception )

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.

Parameters

exception

Exception to throw into the generator.

Return Values

Returns the yielded value.

Changelog

Version Description
7.0.0 The exception parameter also accepts Throwable now.

Examples

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

The above example will output:

Foo
Exception: Test
Bar

© 1997–2017 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://secure.php.net/manual/en/generator.throw.php

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部