处理异常,仅在未抛出异常时执行代码

eoi*_*noc 3 php exception-handling try-catch

我的script_a.php:

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

Class1::tryThis() 有类似的东西:

public function tryThis() {
    Class2::tryThat();
    self::logSuccessfulEvent();
}
Run Code Online (Sandbox Code Playgroud)

问题是Class2::tryThat()可以抛出异常.

如果它确实抛出一个异常,那么该行self::logSuccessfulEvent();仍然会被执行.

我如何重构这个代码,以便self::logSuccessfulEvent()只有当没有抛出异常,但在同一时间发生,让script_a.php知道,当一个异常被抛出?

Jef*_*ert 7

无论操作是否成功,此函数都将返回(true = success,false = failure)

public function tryThis() {
   $success = true;

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

   return $success;
}
Run Code Online (Sandbox Code Playgroud)