Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle specific Exceptions in php

Tags:

exception

php

I want to catch a specific Exception and handle it properly. However, I have not done this before and I want to do it in the best way.

Will it be correct to create a separate class something like

 class HandleException extends Exception
{
   //my code to handle exceptions;
}

and in it have different methods handling the different exception cases? As far as I understand, the Exception class is like an "integrated" class in php so it can be extended and if an Exception is caught it is not obligatory to terminate the flow of the program?

And, an instance of this class will be created when an exception is caught? Sth. like

     catch ( \Exception $e ) {
        $error = new HandleException;
    }
like image 378
Dimentica Avatar asked Jul 24 '26 09:07

Dimentica


1 Answers

You CAN extend the basic Exception object with your own, to provide your own exception types, e.g.

class FooExcept extends Exception { .... }
class BarExcept extends Exception { .... }

try {
   if ($something) {
      throw new FooExcept('Foo happened');
   } else if ($somethingelse) {
      throw new BarExcept('Bar happened');
   }
} catch (FooExcept $e) {
    .. foo happened, fix it...
} catch (BarExcept $e) {
    ... bar happened, fix it ...
}

If an Exception is caught, then the program DOESN'T necessarily have to abort. That'd be up to the exception handler itself. But if an exception bubbles always back up to the top of the call stack and ISN'T caught, then the entire script will abort with an unhandled exception error.

like image 165
Marc B Avatar answered Jul 27 '26 03:07

Marc B