【问题标题】:Using continue in try-catch to prevent script termination when exception is thrown在 try-catch 中使用 continue 以防止在引发异常时终止脚本
【发布时间】:2019-06-02 09:37:15
【问题描述】:

我想将旧代码转换为使用异常,但它不应该在抛出异常时停止。这是旧代码:

function update()
{
 foreach ($this->instances as $id => $instance)
 {
  if ($instance->exists())
  {
   if (!$instance->save())
   {
        $this->setError($instance->getError());
        continue;
   }
   continue;
  }
}

如果我想使用 try catch 块,我需要使用 continue 来避免脚本停止吗?这就是 try-catch 的代码:

function update()
{
 foreach ($this->instances as $id => $instance)
 {
  if ($instance->exists())
  {
   try
   {
    $instance->save();
   }
   catch (exception $e)
   {
    echo $e->getMessage();
   }

  }
}

【问题讨论】:

    标签: php try-catch php-7


    【解决方案1】:

    无需添加continue 关键字。

    如果try 块中抛出异常,则将执行catch 块中的代码。之后剩下的代码就会正常执行了。

    阅读section about exceptions in the language reference了解详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-22
      • 2014-12-07
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多