2013-06-12 31 views
8

这个问题是关于对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) { 

} 

那么什么是更好的(或最好的)方式来完成这个,而不需要额外的变量呢?

+1

把它放在try块。如果它可能抛出另一个你不想被外部try块捕获的异常,那么使用一个嵌套的try-catch来捕获该异常。但请注意,您不会将异常用作流量控制。 – ssube

+0

@peachykeen这将无法正常工作,因为异常需要冒泡。 –

+2

听起来很像你使用异常来控制执行过多。你确定你需要扔砖块和后面的冒泡吗?很可能的是,例外*应该被变量和适当的流量控制所取代。 – ssube

回答

4

一种可能性是把try块的方法,如果有异常回报毫无遗漏的错误。

function myFunction() { 
    try { 
     // Code that throws an exception 
    } catch(Exception $e) { 
     return false; 
    } 
    return true; 
} 
+0

这可以通过try/catch来完成吗? – Orangepill

+0

如果异常需要传播,然后只是重新抛出它在捕获 – Orangepill

+0

我更喜欢这个,因为$ myFunctionResult变量将被赋值为返回值myFunction()不会是完全任意的。 –

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; 
    } 
}