略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Generator::throw

2024-11-15

Generator::throw

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

Generator::throw向生成器中抛入一个异常

说明

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

抛出一个异常到生成器并恢复生成器的执行。 与当前 yield 表达式被 throw $exception 语句替换是一样的行为。

如果调用此方法时生成器已经关闭,则将会在调用者的上下文中抛出异常。

参数

exception

抛出异常到生成器。

返回值

返回生成的值。

范例

示例 #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 noteadd a note

User Contributed Notes 3 notes

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

$gen->throw(new Exception('gen throw exception'));
up
-2
gt199899 at gmail dot com
4 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
5 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

官方地址:https://www.php.net/manual/en/generator.throw.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3