在线工具 | 热点资讯 | 网站目录 | 简繁转换 | 英语单词
查询

Fiber::throw()函数—用法及示例

「 在协程中抛出异常 」


函数名:Fiber::throw()

适用版本:PHP 8.1.0 及以上版本

用法:Fiber::throw() 函数用于在协程中抛出异常。它会中断当前协程的执行,并将异常传递到协程的调用者。

示例:

<?php
function taskA() {
    echo "Task A started\n";
    $fiber = Fiber::getCurrent();
    
    try {
        // 执行一些任务
        // ...
        
        // 抛出异常
        Fiber::throw(new Exception("Something went wrong"));
        
        // 这行代码将不会被执行
        echo "Task A completed\n";
    } catch (Exception $e) {
        echo "Caught exception: " . $e->getMessage() . "\n";
    }
    
    echo "Task A finished\n";
}

function taskB() {
    echo "Task B started\n";
    $fiber = new Fiber('taskA');
    $fiber->start();
    
    // 捕获 taskA 中抛出的异常
    try {
        while ($fiber->status() !== Fiber::STATUS_FINISHED) {
            $fiber->resume();
        }
    } catch (Exception $e) {
        echo "Caught exception from taskA: " . $e->getMessage() . "\n";
    }
    
    echo "Task B completed\n";
}

taskB();
?>

输出:

Task B started
Task A started
Caught exception: Something went wrong
Task A finished
Task B completed

在上面的示例中,我们定义了两个协程函数 taskA()taskB()taskB() 启动了 taskA() 的协程,并在 while 循环中通过 resume() 方法来执行 taskA() 协程的代码。当 taskA() 中抛出异常时,它会被 taskB() 中的 catch 语句捕获到,并输出异常信息。然后,taskB() 继续执行剩余的代码。

请注意,Fiber::throw() 只能在当前协程中抛出异常,如果在非协程环境中调用该函数,会抛出 FiberError 异常。

补充纠错
上一个函数: Fiber::__construct()函数
下一个函数: Fiber::suspend()函数
热门PHP函数
分享链接