gpt4 book ai didi

php - 处理异常,并且仅在未抛出异常时才执行代码

转载 作者:可可西里 更新时间:2023-11-01 00:10:22 26 4
gpt4 key购买 nike

我的script_a.php:

try {
Class1::tryThis();
}
catch (Exception $e) {
// Do stuff here to show the user an error occurred
}

Class1::tryThis() 有类似的内容:

public function tryThis() {
Class2::tryThat();
self::logSuccessfulEvent();
}

问题是 Class2::tryThat() 会抛出异常。

如果确实抛出异常,self::logSuccessfulEvent(); 行似乎仍会执行。

我如何重构这段代码,使 self::logSuccessfulEvent() 只在没有抛出异常时发生,同时让 script_a.php 知道何时抛出异常

最佳答案

此函数将返回操作是否成功(true = 成功,false = 失败)

public function tryThis() {
$success = true;

try {
Class2::tryThat();
self::logSuccessfulEvent();
} catch( Exception $e) {
$success = false;
}

return $success;
}

关于php - 处理异常,并且仅在未抛出异常时才执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9688005/

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