Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using custom exception class in php?

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.

like image 332
hjdm Avatar asked Sep 17 '10 11:09

hjdm


2 Answers

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);
  }
}
like image 114
Mchl Avatar answered Oct 03 '22 22:10

Mchl


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.

like image 33
thomasmalt Avatar answered Oct 03 '22 22:10

thomasmalt