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

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

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

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

In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

所以,一个就够了