2016-01-14 27 views
0

我在一个类中有一个简单的函数。我试图通过使用try/catch来增加异常处理。我的问题是,从try/catch返回并没有停止函数中的处理。这里是我的代码:PHP从函数返回并停止处理

class Config { 

public static $configarray; 

function setConfig($json_path) { 
    try { 
     file_get_contents($config_file); 
    } catch (Exception $e) { 
     die("Config File not found"); 
     return null; 
    } 
    $json = file_get_contents($json_path); 
    try { 
     json_decode($json,TRUE); 
    } catch (Exception $e) { 
     die("Invalid Config file. Check your JSON."); 
     return null; 
    } 
    self::$configarray = json_decode($json,TRUE); 
}  

} //类

末当我运行

Config->setConfig('test.json') 

我得到这些错误:

PHP Warning: file_get_contents(test.json): failed to open stream: No such file or directory in /Config.php on line 30 
PHP Warning: file_get_contents(test.json): failed to open stream: No such file or directory in /Config.php on line 36 

我总是想打印“配置文件未找到“如果找不到该文件。 如何捕捉异常并防止在函数中进一步处理?

+1

警告并不是例外,它们的默认处理方式不同。请参阅下面的链接...... – rjdown

+1

可能重复的[我可以尝试/发现警告吗?](http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning) – rjdown

回答

0

documentation on file_get_contents(),该函数返回读取数据或FALSE的失败,所以你的情况没有一个例外catch,因此该代码路径不会被执行。实际上,您会收到警告信息,但没有任何代码的错误消息。

为了正确处理案例,Chris的建议是正确的,代码如下所示。同样,你需要保护你的json解码逻辑。

function setConfig($json_path) { 
    $data = file_get_contents($config_file); 
    if ($data === FALSE) { 
     die("Could not read the Config File content"); 
     return null; 
    } 
    self::$configarray = null; 
    $json = file_get_contents($json_path); 
    if ($json !== FALSE) { 
     try { 
      self::$configarray = json_decode($json,TRUE); 

     } catch (Exception $e) { 
      die("Invalid Config file. Check your JSON."); 
      return null; 
     } 
    } 
}