On Exceptions

I've been reading the Proposal for Exceptions in ZF2 and like it. One thing that caught my attention was that it suggests that you can catch an interface. I hadn't heard of that ability before, so I pulled out my trusty text editor to have a play.

Consider this code:

<?php
namespace My; 
 
interface ExceptionInterface {} 
 
class SplExceptionClass extends InvalidArgumentException implements ExceptionInterface {} 
class ExceptionClass extends Exception implements ExceptionInterface {} 

class {
    static function throwAnSplException()
    {
        throw new SplExceptionClass('oops');
    }
    static function throwAMyException()
    {
        throw new ExceptionClass('oops again');
    }
}

Within our My namespace, we have two exception classes and an exception interface that both classes implement. We also define a class \My\A as a vehicle for throwing the exceptions. This is the basis of how ZF2 exceptions will work without all the actual component implementations :)

Let's do some testing to look at what happens:

Test 1

try {
    A::throwAMyException();
}
catch (ExceptionClass $e) {
    echo "Caught \\My\\ExceptionClass\n";
}

As expected, this works. We catch the \My\ExceptionClass exception that was thrown.

Test 2

try {
    A::throwAnSplException();
}
catch (ExceptionClass $e) {
    echo "Caught \\My\\ExceptionClass\n";
}

As expected, we fail to catch \My\SplExceptionClass exception that was thrown as it is not related to the \My\ExceptionClass that we are trying to catch.

Test 3

try {
    A::throwAnSplException();
}
catch (ExceptionInterface $e) {
    echo "Caught \\My\\ExceptionInterface\n";
}

This time we are catching the \My\ExceptionInterface and it works! This surprised me and is very handy.

We now have the ability with ZF2 to be able to use different exception classes to represent different error types rather than using string comparison and, at the same time, we can have a single catch() for when we don't need that level of granularity.

If you would like to comment on this article, please ping me on twitter.
If your response won't fit into 140 characters, write a blog post and then ping me!