无法捕获异常

时间:2009-11-25 18:36:17

标签: php exception

为什么不打印以下“错误!”但只打印'未能打开的流...'警告?

try {
    file_get_contents('www.invalid-url.com');
} catch (Exception $e) {
    echo 'Error!';
}

3 个答案:

答案 0 :(得分:3)

file_get_contents不会抛出异常,但如果失败则返回FALSE。 file_get_contents是一个非常原始的函数。如果您需要更高级的反馈,请使用cURL

E.g。像这样的东西:

$curl = curl_init('your URL here');

// Return the output to a string instead of the screen with CURLOPT_RETURNTRANSFER
curl_setopt($pCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($pCurl, CURLOPT_TIMEOUT, 10);

$content = curl_exec($curl);
$info = curl_getinfo($curl);

if($info['http_code'] === 200)
{
    return $content;
}

答案 1 :(得分:2)

错误时返回FALSE,它不会抛出异常。

所以你可以使用@来抑制警告(如果需要)并检查结果以查看是否有错误

$content = @file_get_contents('http://www.example.com');
if ( $content === FALSE ){
    echo "Error!";
}

答案 2 :(得分:0)

PHP默认情况下不使用异常,而是使用错误消息机制。如果您想要例外,可以使用http://php.net/manual/en/class.errorexception.php

中的自定义错误处理程序

关闭错误消息并检查返回代码的PHP方式越多。关闭可以通过error_reporting(0);ini_set('display_errors', false);或使用@运营商在全球范围内完成。

<?php
if (!@file_get_contents(....)) {
    echo "ERROR";
}
?>
相关问题