Skip to content

Herman J. Radtke III

Using SPL Exceptions

Brandon Savage has a great series of posts on using exceptions in PHP.  Unfortunately, he does not introduce the SPL exceptions into the discussion.

The Standard PHP Library (SPL) has quite a few exception classes that are useful right out of the box.  Additionally, these exceptions can be extended just like the Exception and ErrorException classes.

My favorite is the InvalidArgumentException.  I use this exception if some parameter to a function or method is not what I expected.


If you are using the __call() magic method, the BadMethodCallException is another great built-in exception to use.

class Foo
{
    public function __call($name, $params)
    {
        if (!method_exists($this, $name)) {
            throw new BadMethodCallException(
                "Method $name does not exist");
        }
    }
}

The SPL exception classes are a great alternative to writing your own exceptions classes. For some more examples you can check out PHPUnit. Sebastian Bergmann uses a lot of SPL exceptions in his code there.