How to catch an exception from another class method PHP

class, exception, oop, php

Solution

If you are catching the Exception inside a namespace, make sure that you fall back to the global namespace:

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

You can also have a look at the following resources:

- Why isn't my Exception being caught by catch?

- http://php.net/manual/en/language.exceptions.php, top note by user zmunoz

Problem

I'm having trouble catching an exception in PHP Here's my code. ``` try { require $this->get_file_name($action); } catch (Exception $e) { //do something// } ``` and the method being called ``` 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; } } ``` Resulting in: ``` Fatal error: Uncaught exception 'Exception' with message $action was not found.' Exception: The file for this $action was not found. ``` However If I put a try-catch block inside of the function and call the function, I'm able to catch the exception no problem. What am I doing wrong?

Original source

Related problems