php - 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>";
}
解决方案
使用多次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
}
推荐阅读
- javascript - Nextjs 创建一个只处理没有视图的代码的 url
- javascript - Intersection Observer 针对不同窗口大小进行微调
- google-cloud-platform - 在谷歌云中选择 api 的区域
- javascript - 当屏幕尺寸发生变化时触发 useEffect
- python - 为什么我的 Lifo Queue 中的项目会发生变化而不参考它们?
- python - 如何在 OpenCV Python 中创建不同颜色的帧?
- tabulator - 加载表格后更改占位符文本。因此,占位符文本的两个值
- python - 如何从函数列表中组成嵌套函数 g=fn(...(f3(f2(f1()))...) [f1, f2, f3,...fn]
- typescript - 无服务器:编译 TypeScript 时包含资产文件
- callback - 使用 plotly express 并在一页上有多个图表时非常随机地出现导入错误