首页 > 解决方案 > 在抛出异常时在 try-catch 中使用 continue 来防止脚本终止

问题描述

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

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();
   }

  }
}

标签: phptry-catchphp-7

解决方案


无需添加continue关键字。

如果块中抛出异常,try块中的代码catch将被执行。之后,其余代码将正常执行。

有关详细信息,请阅读语言参考中有关异常的部分


推荐阅读