21 March 2017

Why is it important to understand how PHP matches a catch block?

Image: Pixabay
PHP allows you to have multiple catch blocks.  The manual says that when an exception occurs PHP will try to find the first matching exception block, but it isn't entirely clear on exactly how  PHP matches "catch" blocks when handling exceptions.

Why is it important to understand how PHP matches a catch block?

It really relates to the fact that you are able to extend the base "Exception" class in PHP to make your own classes.  Throwing exceptions that are specific is good practice because it allows you to write catch blocks that are focused on solving just one sort of problem at a time.  The SPL exceptions are a good example of hierarchical exception inheritance in case you're wanting to see some practical usage.

In PHP a catch block is a match for an exception if the exception class is either the same as or inherits from the class in the catch clause.

Here's a trivial example:

In this example I've set up an exception class that extends the base exception class.  I'm throwing an instance of this child exception.  If I didn't know that PHP will match it's parent class I would expect the message "Child exception" to be output.

In actual fact if you run this code (here) you will see that the message "Parent exception" is output because PHP has matched MyException with its parent class.

The PHP manual doesn't make this explicit or obvious when discussing catch blocks or exception inheritance but it's one of those things that's always handy to know.

This implies that when we're coding multiple catch blocks we should place the more general parent classes at the bottom of the list.  This prevents them from catching exceptions that are meant for their children.

I discuss this and other gotchas  in my study guide for the Zend certification exam.