Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an exception from another class method PHP

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?

like image 982
Nick Shears Avatar asked Oct 28 '25 10:10

Nick Shears


2 Answers

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
like image 138
jim_kastrin Avatar answered Oct 31 '25 01:10

jim_kastrin


I can't see all of the class body but If You want to use method out of the class it should be Public not Private.

like image 33
Daniel Szantar Avatar answered Oct 31 '25 02:10

Daniel Szantar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!