On his blog today Jani Hartikainen looks at how you can use the SPL exception types to allow for better overall error handling in your application. Things like BadMethodCallException and OutOfBoundsException make the errors much more descriptive.
Since PHP 5, there has been a bundle of built-in exceptions – the "SPL exceptions" – in PHP. However, the documentation for these classes is quite lacking in examples, and it can be difficult to understand when you should be using them. The short answer is always.
The list of exception types he recommends include:
- BadMethodCallException
- DomainException
- LengthException
- OutOfRangeException
- UnexpectedValueException
For each he gives an example usage of it, sometimes including a bit of code to illustrate.