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

Nic*_*ars 3 php oop exception class

我在 PHP 中捕获异常时遇到问题

这是我的代码。

try {
require $this->get_file_name($action);
}

catch (Exception $e) {
//do something//
}
Run Code Online (Sandbox Code Playgroud)

和被调用的方法

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

导致:

Fatal error: Uncaught exception 'Exception' with message $action was not found.'
Exception: The file for this $action was not found.
Run Code Online (Sandbox Code Playgroud)

但是,如果我在函数内部放置一个 try-catch 块并调用该函数,则可以毫无问题地捕获异常。

我究竟做错了什么?

jim*_*rin 8

如果您在命名空间内捕获异常,请确保回退到全局命名空间:

...
}(catch \Exception $e) {
  ...
}...
Run Code Online (Sandbox Code Playgroud)

您还可以查看以下资源: