【问题标题】:Continue code execution after an error and deal with them later in PHP?发生错误后继续执行代码并稍后在 PHP 中处理它们?
【发布时间】:2016-12-19 21:48:16
【问题描述】:

我正在编写一个简单的 php 代码,用于从带有邮件列表的 MySQL 表发送电子邮件;
我正在尽我所能防止错误发生,验证字段并尽我所能防止错误发生。

我将使用 foreach 循环发送每封电子邮件,其中包含姓名和其他相关信息,但我担心出于某种原因,某些电子邮件或姓名可能会引发错误并中途停止我的代码通过列表,让我不知道它停在哪里。

我想知道是否有办法跳过有问题的行并继续发送电子邮件,然后显示有关发送失败的行的详细信息。

我以为我可以使用 Try/Catch,但我找不到是否可以在异常之后继续代码,也找不到如何附加错误消息以显示在最后。

如果这不是处理可能出现的错误的好方法,那么最好的方法是什么?

提前致谢!

【问题讨论】:

    标签: php mysql email try-catch


    【解决方案1】:

    您是否尝试过 try/catch 解决方案?这里完美描述:http://php.net/manual/en/language.exceptions.php

    “正常执行(当 try 块内没有抛出异常时)将在按顺序定义的最后一个 catch 块之后继续。”

    所以你可以将你的发送函数放入 try/catch 块中 -> 如果发生错误,将错误写入数组并在 foreach 循环之后打印数组。

    【讨论】:

      【解决方案2】:

      您可以使用 try cacth 忽略错误

      try {
          // your code here
      } catch (Exception $e) {
          // here do nothing
      }
      

      如果您想稍后处理错误,您可以向数组添加异常并在 finally 块上处理错误。

      try {
          // your code
      } catch (Exception $e) {
          // add error to error array
      } finally {
          // deal with error array
      }
      

      http://php.net/manual/pt_BR/language.exceptions.php

      【讨论】:

        【解决方案3】:

        try/catch 肯定会为此工作。由于您特别关注异常后的继续执行,因此请记住 try 块中包含的内容很重要。例如:

        $array = [1, 2, 3, 'string', 5, 6];
        
        try {
            foreach ($array as $number) {
                if (is_string($number)) throw new Exception("Not a number", 1);            
                echo $number;
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        

        你会看到这段代码

        123不是数字

        因为处理完异常后,会在catch块之后继续执行,而不是在抛出异常的地方继续执行。

        然而,在 foreach 循环中使用 try/catch

        foreach ($array as $number) {
            try {
                if (is_string($number)) throw new Exception("Not a number", 1);            
                echo $number;
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
        

        异常之后循环会继续,你会看到

        123不是数字56

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-22
          • 1970-01-01
          • 2021-05-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多