【问题标题】:PHP Try and Catch ExceptionPHP 尝试并捕获异常
【发布时间】:2013-12-06 18:20:24
【问题描述】:

使用下面的代码,我试图数 -0.25、-0.333、-0.5、-1,抛出异常,然后继续数 1、0.5、0.333、0.25。

到目前为止,我遇到了异常,然后我不知道如何继续计数。

function inverse($x)
{
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    for ($i=-4; $i<=4; $i++) {
        echo inverse($i) . "\n<br>";
        }
}

catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n<br>";

}

// Continue execution
echo 'Hello World';

?>

我尝试将echo inverse(-$i) . "\n&lt;br&gt;"; 添加到 TRY 部分,但没有成功。它继续计数,但不捕获异常。

有什么建议吗?

谢谢!

【问题讨论】:

    标签: php exception try-catch


    【解决方案1】:

    你的catch在for循环之外,所以一旦异常被捕获,for循环就结束了。

    试试

    for ($i=-4; $i<=4; $i++) {
        try {
            echo inverse($i) . "\n<br>";
        } catch (Exception $e) {
            echo 'Caught exception: ', $e->getMessage(), "\n<br>";
        }
    }
    

    改为。

    【讨论】:

      【解决方案2】:

      或者只是像这样更改您的代码:

       function inverse($x)
          {
              if (!$x) {
                  return 'Division by zero.';
              }
              else return 1/$x;
          }
      
          try {
              for ($i=-4; $i<=4; $i++) {
                  echo inverse($i) . "\n<br>";
                  }
          }
      
          catch (Exception $e) {
              echo 'Caught exception: ', $e->getMessage(), "\n<br>";
      
          }
      
          // Continue execution
          echo 'Hello World';
      
          ?>
      

      【讨论】:

        【解决方案3】:

        try|catch 放入循环中:

        for ($i=-4; $i<=4; $i++) {
            try {
                echo inverse($i) . "\n<br>";
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n<br>";
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-12-05
          • 2014-05-11
          • 1970-01-01
          • 1970-01-01
          • 2018-02-06
          • 2012-11-02
          • 1970-01-01
          • 1970-01-01
          • 2021-12-13
          相关资源
          最近更新 更多