Wednesday, March 18, 2009

PHP's ErrorException class

Did you know PHP has an ErrorException class that solves the problem of throwing exceptions from an error handler function?

What problem?

Well, if you throw a normal Exception from such a handler, the file name and line number of the Exception will be set to match the file and line where the Exception was actually thrown and not the place where the error happened. There was no way to extend an Exception class and provide the correct information as Exception's $file and $line properties are private and there are no setter for them, only getters.

ErrorException solves this problem by overriding the Exception constructor, allowing us to pass up to five arguments. From these five arguments, four have the same meaning as the four arguments passed to the error handler function: $errno, $errstr, $errfile, $errline. By passing along these arguments to the ErrorException constructor we get a more meaningful exception from our error handler.

2 comments:

Tudor said...

They're considering to rewrite Zend Frameworks's Zend_Exception class to extend from ErrorException instead of Exception to make use of these features.

Ionut G. Stan said...

I had no idea about this. But honestly, I don't see the point of it. Why would they want all the framework's exception classes to be derived from ErrorException (almost all extend from Zend_Exception)? It's semantically incorrect.

Anyway, to be honest I don't really like the Exception system in ZF. There are places where they use the same Exception class for unrelated errors/error contexts. The only difference is made by the exception's message.

Post a Comment