函式名: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
異常。