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


How to catch an exception from another class method 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) {
  ...
}...

您还可以查看以下资源:

  • 为什么不是';我的例外被捕获了吗
  • http://php.net/manual/en/language.exceptions.php,用户最重要的注释zmunoz

我看不到所有的类主体,但如果你想在类外使用方法,它应该是Public而不是Private。

尝试检查您试图获取的文件是否存在:

var_dump($file = '../private/actions/actions_'.$this->group.'.php');

IMO此路径中没有文件