抛出异常和返回类型

Dav*_*vid 4 php exception-handling

抛出新异常时,如果不需要抛出异常,最好只返回true.或者,最好返回false而不是抛出异常.我正在使用PHP.

irc*_*ell 13

这一切都取决于你在做什么.就个人而言,我一直使用它们,所以我不必检查返回值(一个愚蠢的,但说明性的例子):

function ArrayToObject(array $array) {
    $obj = new StdClass();
    foreach ($array as $key => $value) {
        if (!is_string($key)) {
            throw new Exception('Expects only string keys in the array');
        }
        $obj->$key = $value;
    }
    return $obj;
}
Run Code Online (Sandbox Code Playgroud)

那样,我可以这样做:

$array = array('foo' => 'bar');
try {
    echo ArrayToObject($array)->foo; //Prints "bar"
} catch (Exception $e) {
    //Handle error here
}
Run Code Online (Sandbox Code Playgroud)

它让您不必担心错误检查结果.您可以直接处理catch块中的错误.

所以不,不要根据异常改变你要返回的内容......让异常处理错误并为你改变工作流程......

一个更真实的例子(伪代码):

try {
    open database connection;
    send query to database;
    operate on results;
} catch (DatabaseConnectionException $e) {
    handle failed connection here;
} catch (DatabaseQueryException $e) {
    handle failed query here;
} catch (Exception $e) {
    handle any other errors here;
}
Run Code Online (Sandbox Code Playgroud)

显然,假设您的数据库函数/方法抛出这些异常......