简体   繁体   English

可以尝试使用catch来处理异常吗?

[英]Can try catch be used this way to handle exceptions?

Try catch is used for handling exceptions but could it be used this way too? Try catch用于处理异常,但是也可以这样使用吗?

private $blockUrl = [];   

public function doSomething($urls) {
    try {
        foreach ($urls as $key => $url) {
            if (in_array($url, $this->blockUrl)) continue;
            $meta[$url] = get_meta_tags($url);
            unset($urls[$key]);
        }
    } catch (Exception $e) {
        $this->blockUrl[] = $url;
        return $this->doSomething($urls);
    }

    return $meta;
}

So basically what this does is that it gets the meta tags of the urls passed on to the method. 因此,基本上,此操作是获取传递给该方法的url的元标记。 Then should an exception on the get_meta_tags occur, an exception will be thrown and that url that caused the exception will be put into an array $this->blockUrl . 然后,如果在get_meta_tags发生异常,则将引发异常,并将导致异常的URL放入数组$this->blockUrl Then it will call the same method again but this time, only the remaining urls will be validated again. 然后它将再次调用相同的方法,但是这一次,将仅再次验证剩余的URL。

Is this a correct and efficient way to do this logic? 这是执行此逻辑的正确有效的方法吗?

I used try catch here because of sometimes I get curl errors on the get_meta_tags and I just want to skip those urls that has those errors and continue with the flow. 我在这里使用try catch是因为有时我会在get_meta_tags上遇到curl错误,而我只想跳过那些包含这些错误的URL,然后继续进行操作。

As I suggested in my comment, you can do the error checking inside the loop, and just skip over any bad ones. 正如我在评论中所建议的那样,您可以在循环内进行错误检查,并跳过所有不良情况。 This allows you to get rid of the $blockUrl array, unless you need it elsewhere. 这使您可以摆脱$blockUrl数组,除非您在其他地方需要它。

public function doSomething($urls) {
    $meta = array();
    foreach ($urls as $key => $url) {
        try {
            $result = get_meta_tags($url);
            $meta[$url] = $result;
        } catch (Exception $e) {
            continue;
        }
    }
    return $meta;
}

Put the try/catch inside the loop: try/catch放入循环中:

public function doSomething($urls) {
    $meta = [];

    foreach ($urls as $url) {
        try {
            $meta[$url] = get_meta_tags($url);
        } catch (Exception $e) {
            //
        }
    }

    return $meta;
}

Don't forget to initialize the $meta array, otherwise you might get an errer when you try to return an undefined variable. 不要忘记初始化$meta数组,否则当您尝试返回未定义的变量时,可能会遇到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM