开发者

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

开发者 https://www.devze.com 2023-01-16 08:19 出处:网络
In some libraries it is common practice to make custom Exception classes for ev开发者_运维百科ery error condition, like:

In some libraries it is common practice to make custom Exception classes for ev开发者_运维百科ery 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.


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);
  }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消