好了,我已经看了stack, google等....这个问题似乎没有"正确"的答案!
自从我开始学习PHP
以来,我一直使用try{}catch()
块。有些人说这是错的,有些人说这是好的。我会继续使用它们,但在我继续使用之前,我想知道我是否正确使用它们?我嵌套try { try{}catch() {} }catch(){}
彼此,这是一个很好的做法吗?这样做会使代码有点混乱!如果有更好的方法来做我正在做的事情,我肯定会考虑的。
这里是一个代码块,我正在工作的时刻,我在嵌套try块错误吗?
try{
$sql = "select * from users where email = '$email'";
$stmt = $dbConnection->query($sql);
$returned = $stmt->fetch();
if($stmt->rowcount() == 0){
echo "ERROR";
}else{
try{
$adminId = $returned['uID'];
$auth_key = generateAuth();
$sqlHousehold = "INSERT INTO household (adminId, hhName,auth_key) VALUES ($adminId, '$hhName', '$auth_key')";
$stmt = $dbConnection->query($sqlHousehold);
$id = $dbConnection->lastInsertId();
/*Update the newly created householdID into the admins column*/
$sql = "UPDATE users set hhID = $id where uID = $adminId";
$stmt = $dbConnection->query($sql);
/*
RETURN the group auth key (Share this to members of fam) + user auth key (store on phone)
*/
return '{"user_auth_key":"'.$user_auth_token.'", "group_auth_key":"'.$auth_key.'"}';
}catch(PDOException $e){
}
}
}catch(PDOException $er){
exit("PDO ExCEPTION !^!^!^!^! " .$er);
}
不需要inner try catch
块。列出outer catch block
中的所有exceptions
。
在try catch
中另一个try catch
块将增加开销&将代码设置为slower
。最好只使用外部的try catch
不需要嵌套异常,您可以对同一个try
使用多个catch
语句,得到相同的结果。例如
try {
// some code that might throw exceptions
} catch(ExceptionType1 $ex) {
// handle the first exception
} catch(ExceptionType2 $ex) {
// handle the second exception
} catch(ExceptionTypeN $ex) {
// handle the last exception
} catch(Exception $ex) {
// catch all other exceptions
}
但是,对于您的特定情况,您在两个try/catch
中捕获相同类型的异常(PDOException)。它不需要内部try/catch
块,因为它已经由外部try/catch
块处理了。
PDOException
表示大多数时候连接数据库或查询数据时出现的问题,这可以在一个地方处理。
我的意见是否定的。
这只是不必要地增加了开销。我知道它并不总是最简洁或最有用的选项,但switch实际上比if else语句运行得更快:http://php.net/manual/en/control-structures.switch.php
而且,如果长此以往它变得更大,在那里放置调试代码将会减慢速度。如果代码可以工作,为什么要浪费资源调试它呢?
编辑
简单的错误处理逻辑:// Error handlers
function doError ($e) {
$_SESSION['error'] = $e;
header('Location: http://website.com/error.php');
exit;
}
function getError () {
if (isset($_SESSION['error']) {
return $_SESSION['error'];
} else {
die('Fatal Error!');
exit;
}
}
function clearError () {
unset($_SESSION['error']);
}
// Error handling when conditions are not met
if (!myCondition()) {
doError('Condition not met!');
}
// Error template / error.php
$e = getError();
$html = '
<!DOCTYPE html>
<html>
<title>Fatal Error!</title>
<body>
<h1>A fatal error occurred</h1>
<p>'.$e.'</p>
</body>
</html>
';
echo $html;
clearError();
外部try-catch块将捕获其内部捕获的所有异常。如果catch中的动作在代码的不同部分会有所不同,那么嵌套它们可能会很有用。否则,如果两个catch块都要做同样的事情,那么这样做就没有意义了。