【问题标题】:How to catch an exception from another class method PHP如何从另一个类方法 PHP 中捕获异常
【发布时间】:2013-08-13 16:21:57
【问题描述】:

我无法在 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 块并调用该函数,我能够捕获异常没有问题。

我做错了什么?

【问题讨论】:

  • 把你的 try/catch 块放在调用代码中
  • Cannot Reproduce 你确定提供的代码示例是被调用的那个吗? (可能是子类) 您收到的异常消息似乎与应该抛出的不匹配。 (未评估的$action

标签: php class oop exception


【解决方案1】:

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

...
}(catch \Exception $e) {
  ...
}...

您还可以查看以下资源:

【讨论】:

    【解决方案2】:

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

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

    IMO 此路径中没有文件

    【讨论】:

      【解决方案3】:

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

      【讨论】: