只有在没有抛出异常的情况下,才能在try块之外执行代码的最简洁方法

km6*_*zla 14 php exception-handling exception try-catch

这个问题是关于在没有抛出异常的情况下在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
}
Run Code Online (Sandbox Code Playgroud)

这是@webbiedave在回答问题php try .. else时建议的方法.由于使用了额外的$caught变量,我发现它不能令人满意.

$caught = false;

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

if (!$caught) {

}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

function myFunction() {
    try {
        // Code  that throws an exception
    } catch(Exception $e) {
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)