A Primer on PHP Exceptions

The original article is here:

http://nitschinger.at/A-primer-on-PHP-exceptions

The article explains the structure of the exceptions very well, with this simple list summing up what many pages of PHP manual pages does not make very clear:

[text]
– Exception
– ErrorException
– LogicException
– BadFunctionCallException
– BadMethodCallException
– DomainException
– InvalidArgumentException
– LengthException
– OutOfRangeException
– RuntimeException
– OutOfBoundsException
– OverflowException
– RangeException
– UnderflowException
– UnexpectedValueException
[/text]

The article describes in detail what the structure means for your exception handling and how to take advantage of it.

It also introduces the idea of extending these exceptions into your own custom namespace. Try not to create a gazzilian of your own specific exceptions (e.g. in portable libraries) without extending this basic structure. Taking this approach makes exception handling a lot more flexible, but also reduces the unexpected for the next developer.

Update:

The PHP documentation, since the launch of the new PHP site theme, shows the structure of the SPL exceptions a lot more clearly now. You can find the “SPL Exceptions Class Tree” here:

http://php.net/manual/en/spl.exceptions.php

Note also that as well as the exception hierarchy, they can be cascaded at run-time, so a stack of exceptions can be retained from an initial exception right up to the top where it may be finally logged or reported to a user. This is often called “nesting”, but I think that’s a bit of a misnomer. “nesting” refers more to an hierarchy of extended objects, and the hierarchy is defined in the code. The cascade of exceptions is something that happens at run-time, and the cascade could drag in any number of unexpected exceptions.

No comments yet.

Leave a Reply