What happens with set_error_handler() on PHP7 now that all errors are exceptions?
Aaron Piotrowski (the guy who made the new Error-Exception system) has a great blog on this. I think the key point you need to understand is this
In PHP 7, an exception will be thrown when a fatal and recoverable error (
E_ERROR
andE_RECOVERABLE_ERROR
) occurs, rather than halting script execution. Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately halting script execution. An uncaught exception will also continue to be a fatal error in PHP 7. This means if an exception thrown from an error that was fatal in PHP 5.x goes uncaught, it will still be a fatal error in PHP 7.Note that other types of errors such as warnings and notices remain unchanged in PHP 7. Only fatal and recoverable errors throw exceptions.
To put this a different way consider this
set_exception_handler()
- Function to handleException
s by default (as of PHP 7.0 this can handle allThrowable
s, so it can catch recoverable errors)set_error_handler()
- Function to handle recoverable errors
In other words, their functionality didn't change. Anything that triggers them in PHP5 will trigger them in PHP7, it's just that, now, you can use a try-catch
block at the script level to handle a specific error.
http://php.net/manual/en/language.errors.php7.php is a good read on this:
PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.
As with normal exceptions, these Error exceptions will bubble up until they reach the first matching catch block. If there are no matching blocks, then any default exception handler installed with set_exception_handler() will be called, and if there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.
This means that errors are not technically exceptions, however they can be caught like exceptions (which is a nice feature).
For example the following should work as before:
set_error_handler('handleError');
try {
// raise error
} catch (Exception $e) {
// won't catch error
}
However the following should also be possible
try {
// raise error
} catch (Exception $e) {
// won't catch error
} catch (Error $e) {
handleError();
}
You can use php trigger_error('test error')
to see what happen when error is not handled by php set_exception_handler()