Pragmatism in the real world

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 A {
    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 MyA 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 MyExceptionClass exception that was thrown.

Test 2

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

As expected, we fail to catch MySplExceptionClass exception that was thrown as it is not related to the MyExceptionClass 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 MyExceptionInterface 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.

5 thoughts on “On Exceptions

  1. For what it's worth, I've done something similar in a REST approach: Exception classes for handling possible errors (e.g. HTTP 404 would throw a NotFoundException and so on). Since every one of this classes extends a BaseException class, I just need to worry about catch()'ing a single type.

    However, I've heard/read a lot about catch()'ing every exception type that's possible to be thrown in a single try{} block as a good practice. Although it just don't look that practical, it would be something "nice" to be done.

    Would you comment that?

    Regards,
    George

  2. George,

    I think it's only worth catching different types of exceptions if your app is going to do something different as a result of the catch.

    Arne,

    I haven't a clue!

    Regards,

    Rob..

Comments are closed.