basagabi
basagabi

Reputation: 5064

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?

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. 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. Then it will call the same method again but this time, only the remaining urls will be validated again.

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.

Upvotes: 0

Views: 327

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 220136

Put the try/catch inside the loop:

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.

Upvotes: 1

miken32
miken32

Reputation: 42744

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.

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

Upvotes: 2

Related Questions