我在PHP中捕获异常时遇到问题
这是我的代码.
try {
require $this->get_file_name($action);
}
catch (Exception $e) {
//do something//
}
private function get_file_name($action) {
$file = '../private/actions/actions_'.$this->group.'.PHP';
if (file_exists($file) === false) {
throw new Exception('The file for this '.$action.' was not found.');
}
else {
return $file;
}
}
导致:
Fatal error: Uncaught exception 'Exception' with message $action was not found.'
Exception: The file for this $action was not found.
但是如果我在函数内部放置一个try-catch块并调用该函数,我就能捕获异常没问题.
我究竟做错了什么?
解决方法:
如果要在命名空间内捕获Exception,请确保回退到全局命名空间:
...
}(catch \Exception $e) {
...
}...
您还可以查看以下资源:
> Why isn’t my Exception being caught by catch?
> http://php.net/manual/en/language.exceptions.php,用户zmunoz的前调