如何正确使用Try-Catch Exception?

时间:2011-05-14 20:02:25

标签: php facebook try-catch

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

在上面的代码中,当'try'块中的代码失败时,控件不会传递给'catch'块。我输出的错误是因为https://graph.facebook.com/xxxxxx/picture不是有效的JPEG。实际上,如果它不是JPEG,那么在这种情况下它就是GIF。所以有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:7)

imagecreatefromjpeg如果失败则不会抛出异常。有关详细信息,请参阅PHP: How to manage errors gracefully?

最好使用函数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;
}

这样,您可以完全避免这个问题,因为它不会尝试将文件解析为JPEG(如果不是一个)。

相关问题