views:

49

answers:

2

In some libraries it is common practice to make custom Exception classes for every error condition, like:

class FileNotFound_Exception extends Exception {}

You can handle certain type of Exception, however you cannot read all source code of all libraries to remember each Exception class, and cannot take full advantage of using custom Exceptions. Most of time I just catching them with base Exception class:

catch (Exception $e)
{
    // log and display friendly error
}

Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks? I like Exceptions, but don't know how to use them properly. Thank you.

+2  A: 

The benefit of having your own Exception class is that you, as the author of the library, can catch it and handle it.

try {
   if(somethingBadHappens) {
     throw MyCustomException('msg',0)
   }
} catch (MyCustomException $e) {
  if(IcanHandleIt) {
    handleMyCustomException($e);
  } else {
    //InvalidArgumentException is used here as an example of 'common' exception
    throw new InvalidArgumentException('I couldnt handle this!',1,$e);
  }
}
Mchl
+1  A: 

Well, custom exception classes lets you route your errors properly for better handling.

if you have a class

class Known_Exception extends Exception {}

and a try catch block like this:

try {
    // something known to break
} catch (Known_Exception $e) {
    // handle known exception
} catch (Exception $e) {
    // Handle unknown exception
}

Then you know that Exception $e is an unknown error situation and can handle that accordingly, and that is pretty useful to me.

thomasmalt