开发者

How to use Try-Catch Exception correctly?

try{
  $src = imagecreatefromjpeg('https://graph.facebook.com/'.$jsonfriends["data"][$randf]["id"].'/picture');
} catch (Exception $z){
  $src = imagecreatefromgif('https://graph.facebook.com/'.$jsonfriends["data"][$randf]["id"].'/picture');
}

In the above code, when the code in the 'try' block fails, the control is not passing to the 'catch' block. I'm getting output 开发者_如何学Pythonas error as https://graph.facebook.com/xxxxxx/picture is not a valid JPEG. Actually, if its not a JPEG, it would be GIF in this context. So can anyone help me regarding this?


imagecreatefromjpeg doesn't throw an exception if it fails. For more information on that, see PHP: How to manage errors gracefully?.

You'd be better off using a function mentioned in the comments of the PHP documentation of the function:

function open_image ($file) {
    $size = getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
            break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
            break;
        case "image/png":
            $im = imagecreatefrompng($file); //png file
            break;
        default: 
            $im=false;
            break;
    }
    return $im;
}

This way, you avoid the problem altogether, as it simply doesn't try to parse the file as a JPEG if it isn't one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜