php try catch无法正常工作

php try catch无法正常工作,php,try-catch,file-get-contents,Php,Try Catch,File Get Contents,我有这样的代码: try { $providerError = false; $providerErrorMessage = null; $nbg_xml_url = "http://www.somesite.com/rss.php"; $xml_content = file_get_contents($nbg_xml_url); // ... some code stuff } catch (Exception $e) { $provide

我有这样的代码:

try {   
    $providerError = false;
    $providerErrorMessage = null;
    $nbg_xml_url = "http://www.somesite.com/rss.php";
    $xml_content = file_get_contents($nbg_xml_url);
    // ... some code stuff
} catch (Exception $e) {
    $providerError = true;
    $providerErrorMessage = $e -> getMessage();
    $usd = 1;
    $rate = null;
    $gel = null;
} finally {
    // .. Write in db 
}`
问题是,当
file\u get\u contents
无法读取url时(可能是站点没有响应或类似的情况…),我的代码写入错误:
无法打开流:HTTP请求失败和执行直接转到最终块绕过catch块,而不输入它


有什么想法吗?

您可以设置一个空的错误处理程序来防止警告,然后在失败时抛出一个自定义异常。在这种情况下,我会编写一个自定义的
文件\u get\u content
,如下所示:

function get_file_contents($url) {

    $xml_content = file_get_contents($url);

    if(!$xml_content) {
        throw new Exception('file_get_contents failed');
    }

    return $xml_content;
} 
并且会在你的街区使用它:

set_error_handler(function() { /* ignore errors */ });

try {   
    $providerError = false;
    $providerErrorMessage = null;
    $nbg_xml_url = "http://www.somesite.com/rss.php";

    $xml_content = get_file_contents($nbg_xml_url); //<----------

    // ... some code stuff
} catch (Exception $e) {
    $providerError = true;
    $providerErrorMessage = $e -> getMessage();
    $usd = 1;
    $rate = null;
    $gel = null;
} finally {
    // .. Write in db 
}
请注意,当使用您自己的错误处理程序时,它将绕过

错误报告

设置和所有错误(包括通知、警告等)都将传递给它

$xml_content = file_get_contents($nbg_xml_url);
函数文件\u get\u内容不会引发异常。因此,如果您说找不到该文件,则不会引发异常

从文档中:

如果找不到文件名,将生成E_警告级别错误


此函数在失败时返回读取数据或FALSE。因此,您可以检查$xml\u content是否为FALSE($xml\u content===FALSE),并进行相应的处理。

如果抛出异常,则会在方法调用中处理,因此不会传递给调用方,即此代码块。如果您认为我的答案对您有帮助,欢迎您投票或接受它。
$xml_content = file_get_contents($nbg_xml_url);