如何从另一个类方法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的前调

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...