为嵌套的PDO操作嵌套Try/Catch是个好主意吗


Is it a good idea to nest Try/Catch for nested PDO operations?

在数据库中插入一些值之前,我与PDO进行了多次数据库检查,我不知道一次try/catch是否会捕获嵌套PDO中的所有错误,或者我是否需要为每个PDO进行一次try-catch。这是我现在得到的代码:

try {
$db = connect_db();
$q = "query foobar";
$stm = $db->prepare($q);
$stm->bindParam(1, $foobar);
$status = $stm->execute();
if ($stm->rowCount() == 0) {
    if ($def == 0) {
    $q = "query foobar";
    $stm = $db->prepare($q);
    $stm->bindParam(1, $foobar);
    $stm->bindParam(2, $foobar);
    $stm->bindParam(3, $foobar);
    $stm->bindParam(4, $foobar);
    $status = $stm->execute();
    if ($status) {
        echo "<script>alert('foobar');window.location.assign('admin.php');</script>";
    } else {
        echo "<script>alert('foobar');window.location.assign('admin.php');</script>";
        die();
    }
    } else {
    $q = "query foobar";
    $stm = $db->prepare($q);
    $stm->bindParam(1, $nombre);
    $status = $stm->execute();
    if ($stm->rowCount() == 0) {
        $q = "query foobar";
        $stm = $db->prepare($q);
        $stm->bindParam(1, $foobar);
        $stm->bindParam(2, $foobar);
        $stm->bindParam(3, $foobar);
        $stm->bindParam(4, $user);
        $status = $stm->execute();
        if ($status) {
        echo "<script>alert('foobar.');window.location.assign('admin.php');</script>";
        } else {
        echo "<script>alert('foobar.');window.location.assign('admin.php');</script>";
        die();
        }
    }
    }
} else {
    echo "<script>alert('foobar.'); history.back();</script>";
    die();
}
} catch (Exception $e) {
// Proccess error
$msg = $e->getMessage();
$timestamp = date("Y-m-d H:i:s");
$line = $e->getLine();
$code = $e->getCode();
handle_error($msg, $timestamp, $line, $code);
die("foobar");
}

PDO::ERRMODE_EXCEPTION

除了设置错误代码外,PDO还会抛出一个PDOException,并设置其属性以反映错误代码和错误信息。此设置在调试期间也很有用,因为它将有效地";"爆炸";脚本在错误点,非常迅速地指出代码中潜在的问题区域(记住:如果异常导致脚本终止,事务会自动回滚)。

异常模式也很有用,因为与传统的PHP风格的警告相比,您可以更清楚地构建错误处理,并且与在静默模式下运行并显式检查每个数据库调用的返回值相比,代码/嵌套更少。

因此,一个就足够了