首页 > 解决方案 > Can you use multiple try catch?

问题描述

hello i just want to ask if i can use multiple try catch on my php script without negative out come? i'm currently tasked to maintain a web app, however it was written in POP, so would this result to issues if i do this multiple times? I'm new to my job and i don't wanna loose it please help.

    try{
        mysqli_autocommit($conn,FALSE);
        mysqli_autocommit($conn2,FALSE);
        mysqli_autocommit($conn3,FALSE);

        mysqli_query($conn, "UPDATE table SET field='$variable' WHERE field='$varable2'");

        // Commit transaction
        mysqli_commit($conn);
    }
    catch (Exception $e) {
        $error = $e->getMessage();
        write_mysql_log("Error: $error", $conn3);

        // Rollback transaction
        mysqli_rollback($conn);
        mysqli_rollback($conn2);
        mysqli_rollback($conn3);

        echo "<script>alert('***Process Failed***'); window.location = 'target_page.php';</script>";
    }

    //second try catch
    try{
        mysqli_autocommit($conn,FALSE);
        mysqli_autocommit($conn2,FALSE);
        mysqli_autocommit($conn3,FALSE);

        mysqli_query($conn, "UPDATE table SET field='$variable' WHERE field='$varable2'");

        // Commit transaction
        mysqli_commit($conn);
    }
    catch (Exception $e) {
        $error = $e->getMessage();
        write_mysql_log("Error: $error", $conn3);

        // Rollback transaction
        mysqli_rollback($conn);
        mysqli_rollback($conn2);
        mysqli_rollback($conn3);

        echo "<script>alert('***Process Failed***'); window.location = 'target_page.php';</script>";
    }

标签: php

解决方案


使用多次try catch没有错但不好。请记住,在一次“尝试”中,您可以有多个“捕获”,具体取决于正在发生的异常类型。

try {
   //Operations that are succeptible to throw ExceptionTypeOne or ExceptionTypeTwo
} catch (ExceptionTypeOne $exception) {
   //What to do if ExceptionTypeOne happen
} catch(ExceptionTypeTwo $exception) {
   //And if ExceptionTypeTwo happen
}

推荐阅读