14

这个问题是关于仅在没有抛出异常的情况下在 try 块之外执行代码的最佳方法。

try {
    //experiment
    //can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
    //contain the blast
} finally {
    //cleanup
    //this is not the answer since it executes even if an exception occured
    //finally will be available in php 5.5
} else {
    //code to be executed only if no exception was thrown
    //but no try ... else block exists in php
}

这是@webbiedave针对问题php try .. else建议的方法。由于使用了额外的$caught变量,我觉得它不令人满意。

$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}

那么,在不需要额外变量的情况下,有什么更好(或最好)的方法来实现这一点?

4

2 回答 2

7

一种可能性是将 try 块放入方法中,如果出现异常则返回 false。

function myFunction() {
    try {
        // Code  that throws an exception
    } catch(Exception $e) {
        return false;
    }
    return true;
}
于 2013-06-12T19:23:43.750 回答
0

让你的 catch 块退出函数或(重新)抛出/抛出异常。您也可以过滤异常。因此,如果您的其他代码也抛出异常,您可以捕获并(重新)抛出它。请记住:

  1. 如果没有捕获到异常,则继续执行。
  2. 如果发生异常并被捕获而不是(重新)抛出或新的抛出。
  3. 你不会从 catch 块中退出你的函数。
  4. (重新)抛出任何你不处理的异常总是一个好主意。
  5. 我们应该始终明确地处理异常。这意味着如果您捕获异常,请检查我们可以处理的错误应该是(重新)抛出(n)

我处理您的情况的方式是(重新)从第二条语句中抛出异常。

try {
    $this->throwExceptionA();
    $this->throwExceptionB();

} catch (Exception $e) {
    if($e->getMessage() == "ExceptionA Message") {
        //Do handle code

    } elseif($e->getMessage() == "ExceptionB Message") {
        //Do other clean-up
        throw $e;

    } else {
        //We should always do this or we will create bugs that elude us because
        //we are catching exception that we are not handling
        throw $e;
    }
}
于 2014-07-20T06:46:19.583 回答