【发布时间】:2016-12-14 09:01:59
【问题描述】:
我有以下代码,旨在在 try catch 中运行一些代码。但是,当file_get_content 失败时,它仍然不会进入catch 函数,而是继续运行并显示更多错误(例如property_exists,因为$weatherJson 未定义。
try{
$weatherJson = file_get_contents("http://api.someApi?lat={$this->request->getParam("lon")}&lon={$this->request->getParam("lon")}&appid=abcdefg");
$weatherJson = json_decode($weatherJson);
if (property_exists($weatherJson, 'list')) {
$result->weather = $weatherJson->list[0]->weather[0]->main;
$result->timeStamp = $weatherJson->list[0]->dt_txt;
return $result;
} else {
return "no results found";
}
} catch(\Exception $e) {
echo "something is wrong";
}
【问题讨论】:
-
file_get_contents不会抛出异常 -
try...catch仅在引发异常时有效。file_get_contents失败时不会抛出异常。来自手册@return string The function returns the read data or false on failure. -
你应该考虑阅读手册
-
手册还指出“如果找不到文件名、maxlength 小于零或在流中查找指定偏移量失败,则会生成 E_WARNING 级别错误” 所以你可能会得到
false的结果和一个警告,但仍然没有例外。
标签: php exception exception-handling