gpt4 book ai didi

php - 如何处理其他 try catch block 中的异常?

转载 作者:可可西里 更新时间:2023-10-31 23:45:03 26 4
gpt4 key购买 nike

我的例子:

class CustomException extends \Exception {

}

class FirstClass {
function method() {
try {
$get = external();
if (!isset($get['ok'])) {
throw new CustomException;
}

return $get;
} catch (Exception $ex) {
echo 'ERROR1'; die();
}
}
}

class SecondClass {
function get() {
try {
$firstClass = new FirstClass();
$get = $firstClass->method();
} catch (CustomException $e) {
echo 'ERROR2'; die();
}
}
}

$secondClass = new SecondClass();
$secondClass->get();

这会返回“ERROR1”,但我想从 SecondClass 收到“ERROR2”。

在 FirstClass block 中,try catch 应该处理来自 external() 方法的错误。

我怎样才能做到?

最佳答案

与其打印错误消息并终止整个 php 进程,不如抛出另一个异常并注册一个全局异常处理程序,该处理程序对未处理的异常进行异常处理。

class CustomException extends \Exception {

}

class FirstClass {
function method() {
try {
$get = external();
if (!isset($get['ok'])) {
throw new CustomException;
}

return $get;
} catch (Exception $ex) {
// maybe do some cleanups..
throw $ex;
}
}
}

class SecondClass {
function get() {
try {
$firstClass = new FirstClass();
$get = $firstClass->method();
} catch (CustomException $e) {
// some other cleanups
throw $e;
}
}
}

$secondClass = new SecondClass();
$secondClass->get();

您可以使用 set_exception_handler 注册一个全局异常处理程序

set_exception_handler(function ($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
});

关于php - 如何处理其他 try catch block 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com