Exceptions and the handling thereof…

16 Sep

Exceptions and the Handling Thereof...

Ralph Schindler has an article up about the new Exception features of PHP 5.3, as well as some best practices involving Exceptions. To be honest, I hadn’t realized that new Exception types had been added to the SPL, and when I first read it in Ralph’s article, I thought: “Big whup, extending the good ol’ Exception class is good enough for me.”

But I kept reading and now I’m really excited. See, it’s not just that there are new standard exception types, but there’s now a consensus way to incorporate exceptions into your library code. Zend and Pear seem to be agreeing, and while normally I’m not a fan of either’s code standards, this one I like.

In fact, I’m going to steal Zend’s standard nearly word for word:

  • There WILL NOT be a top level anApp\Exception class
  • Each package WILL define a marker Exception interface; subpackages may optionally define a similar marker interface extending that interface.
  • Each package WILL define a generic <package>Exception class (eg. anApp\SmartObject\Exception), extending \Exception and implementing the component level Exception marker interface.
  • Exceptions extending other SPL exception classes and implementing the marker Exception interface MAYbe created.
    • Exceptions deriving from SPL exception classes SHOULD be named after the SPL exception they extend, but MAY be named uniquely. In most cases, we would recommend using the original SPL exception name to prevent a proliferation of exceptions.
    • Exceptions not named after SPL exceptions WILL be named meaningfully: InvalidTemplateException, UnbalancedTagException, etc. Exception types can be re-used, but only if the name has a similar meaning in each context in which it is used.
  • Because the previous requirement may lead to a proliferation of exception classes, exception classes MAY be grouped into an “Exception” subcomponent. The rule of thumb will be that if the number of exception classes exceeds 1/2 the number of regular classes and interfaces, they should be segregated.

This is exciting because it gives you tons of options for throwing and catching exceptions, and for providing context for your errors in a way other programmers can easily understand.

Now I just need to nail down the package/subpackage/class naming conventions. Woot!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: