告诉服务器在出错时不运行代码

时间:2016-06-04 18:27:56

标签: php

我正在寻找一种方法来告诉服务器在发生错误时死亡。

示例:假设有2个SQL查询。如果其中一个发生错误,我不希望它们都工作,就像没有点击任何内容一样。

示例2:当您在代码中遗漏分号或类似内容时,代码的其他部分仍然有效,并显示不可能的内容。

这样的东西

if (error) { do nothing and go back to index page; }

2 个答案:

答案 0 :(得分:1)

从版本5开始,PHP中提供了异常处理。它允许您在出现问题时(即发生异常时)对代码进行更精细的控制。

将您的代码放入try块中。如果发生错误,那么catch块中的代码将运行。还有一个博克。即finally(PHP 5.5),每次运行代码时都会调用它。您可以按层次结构使用这些块。

有用的链接:https://adayinthelifeof.nl/2013/02/12/php5-5-trycatchfinally/

try {

//Your codes

} catch (Exception $e) {
   //when above codes gives error
   do nothing and go back to index page;
}

答案 1 :(得分:0)

您始终可以发送重定向并致电die()/exit()以停止执行当前脚本。

if (error) {
header("Location: http://example.com/index.php");
die();
}

或者使用try / catch包围你的代码并在catch块中发送重定向:

 try {
      //code where an error could occur

 } catch (Exception $e) {
     header("Location: http://example.com/index.php");
    die();
 }