This is an old revision of the document!
Request for Comments: Exceptions instead of Errors
- Version: 1.0
- Date: 2009-07-24
- Author: Ben Scholzen email@example.com
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/errors_as_exceptions
This RFC will discuss the usage of exceptions instead of the usual, not catchable, errors.
Exceptions are a proper way of handling errors and are used in many other languages exclusivley.
Why do we need exceptions instead of errors?
Currently it is not easy to work around expected errors comming from PHP. This does not include errors like E_NOTICE or E_DEPRECATED, but mainly E_WARNING. We frequently notice this problem in the Zend Framework, where it either is bad to performance to use the shut-up-operator (@) and/or there is just no other way instead of supressing an error.
When, for instance, loading an XML file with simplexml_load_file(), it will throw an E_WARNING when the XML is not valid. When the XML is comming from an external source, you can never be sure beforehand if it will be valid or not, so the only thing you can currently do is supressing the error and checking for the return-value “false”. This error supression not only costs time, but also avoids to check for the type of the error (may it be an invalid XML itself, the XML not conforming to the defined DTD or something else). Another example would be fsockopen(), which, when it times out, not only returns false, but also throws an E_WARNING again.
In all those cases it would be a prefered way to be able to simply catch the error as an exception.
Proposal and Patch
All E_WARNINGS should be replaced by exceptions (preferably, ErrorException). An alternative to keep BC would be to allow the try/catch block to also catch errors (either only E_WARNINGS or also other error levels). In that case, error_reporting() set to 0 should not stop the try/catch block to catch that error.