【问题标题】:Php for loop with try catchphp for 循环与 try catch
【发布时间】:2011-09-20 14:31:38
【问题描述】:

根据其中一位用户的建议,此问题是 this 的延续。

我正在使用下面的 getIDs 函数来处理 id。 CheckValid() 将检查 id 是否是要处理的有效 ID,如果是则将转到下一个 updateUsers()。检查有效只是检查一个条件,如果不是,它会引发异常。 updateUsers() 只是在通过 checkValid() 时更新一个列。

问题 - 如果我从 getIDs() 得到 4 个 id 作为输出,并且使用 execute(),它会处理 2,例如,如果它对 2nd id 失败,它不会继续处理其余 2 个 id 的 ..I希望它继续,所以我注释掉了“在 catch 块中抛出 $e”。

Function execute() { 
 for($i=0 ; $i<count($this->getIDs()); $i++) { 
try {
 $this->checkValid();
 $this->updateUsers(); 
} catch(Exception $e) {
  //throw $e;
}

【问题讨论】:

  • 帮助小猫!不要杀了他们!
  • Aaa 问题出在哪里?似乎您在 catch 块中什么都不做“解决”了它?
  • throw 会中断循环,但抑制错误可能并不明智。

标签: php for-loop


【解决方案1】:

你在 catch 块中尝试过简单的 continue 吗?没有测试,但可能是这样的:

Function execute() { 
 for($i=0 ; $i<count($this->getIDs()); $i++) { 
    try {
     $this->checkValid();
     $this->updateUsers(); 
    } catch(Exception $e) {
     //throw $e;
     continue; // if not working try a continue 2;
    }
  }
} 

【讨论】:

    【解决方案2】:

    听起来您将异常用作布尔值,我建议您避免这样做,因为它很快就会变得混乱,除非您真的需要异常的内容。看看这对您的用例是否有意义(我同意,可能没有)。

    // returns true if valid, false otherwise
    function checkValid(){
        try {
            // do your validation
            return true;
        } catch (Exception $e) {
            // optional: save the exception in case we want to know about it
            $this->last_error = $e;
            return false;
        }
    }
    
    function execute() { 
        for($i=0 ; $i<count($this->getIDs()); $i++) { 
            if($this->checkValid()){
                $this->updateUsers();
            }
            // if you want to do something with an error, simply add an else clause
            // and handle $this->last_error
        }
    }
    

    另外,我显然不知道您的代码或您到底在做什么,但是循环 n 次并在没有参数的情况下调用 checkValid()updateUsers() 似乎是非常糟糕的做法。例如,最好循环遍历 ID 列表并依次检查每个 ID 和用户,如下所示:

    foreach($this->getIDs() as $id){
        if($this->checkValid($id)){
            $this->updateUser($id);
        } else {
            // an advantage of this is now we can know exactly which ID failed,
            // because we have the $id variable
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2021-12-18
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多