微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从另一个类方法PHP中捕获异常

我在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的前调

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐