Dimentica
Dimentica

Reputation: 805

Handle specific Exceptions in 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;
    }

Upvotes: 3

Views: 5737

Answers (2)

Marc B
Marc B

Reputation: 360562

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.

Upvotes: 4

Philipp Palmtag
Philipp Palmtag

Reputation: 1328

From the manual

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

So you can do something like this:

try {
    // some code
} catch ( HandleException $e ) {
    // handle sthis error
} catch ( \Exception $e ) {
    // handle that error
}

This will handle different exceptions. You can also use the finally keyword with newer versions of PHP.

Upvotes: 5

Related Questions