循环内的 PHP try-catch 块 [英] PHP try-catch block inside loop

查看:100
本文介绍了循环内的 PHP try-catch 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果打算在发生异常时循环将结束,那么将 try-catch 块放在循环中与在 php 中用 try-catch 包装循环相比是否效率较低?还是本质上没有区别?

Is it less efficient to put a try-catch block inside of a loop as opposed to wrapping the loop with a try-catch in php if it is intended that the loop will end if an exception occurs? Or is there essentially no difference?

foreach (/*...*/) {
    //...
    try {
        //...
    } catch (/*...*/) {
        break;
    }
    //...
}

对比:

try {
    foreach (/*...*/) {
        //...
    }
}

推荐答案

这完全取决于失败的性质,以及您打算在 catch 中做什么.

That entirely depends on the nature of the failure, and what you intend to do in the catch.

但我会这样概括

  • 如果您希望循环在异常时退出,请将整个循环包装起来
  • 如果您希望循环继续,请不要

在循环中捕获的异常不会隐式中断循环

Exceptions caught inside a loop don't implicitly break the loop

for ($i = 1; $i < 10; $i++) {
    try {
        if ($i % 3 == 0) {
            throw new Exception('BOOM');
        }
        echo $i;
    } catch (Exception $e) {
        echo "Exception at $i";
    }
    echo PHP_EOL;
}

输出:

1
2
Exception at 3
4
5
Exception at 6
7
8
Exception at 9

而那些被在循环之外捕获的人

try {
    for ($i = 1; $i < 10; $i++) {
        if ($i % 3 == 0) {
            throw new Exception('BOOM');
        }
        echo $i, PHP_EOL;
    }
} catch ( Exception $e ) {
    echo "Exception at $i";
}

输出:

1
2
Exception at 3

这篇关于循环内的 PHP try-catch 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆