In the documentation for PHP 7, I noticed that two predefined exceptions, Error
and ErrorException
are almost exactly the same, with ErrorException
having the additional $severity
property and Error
only being introduced in PHP 7 while ErrorException
has existed since PHP 5.1.
From what I understand, Error
is the exception which I should use to catch all internal PHP errors, such as type errors, but I don't get what is the purpose of the ErrorException
exception. What is the use of each of them, and should I base my custom exceptions off of either of them, or should I stick with the usual Exception
?
The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. Exceptions are used to change the normal flow of a script if a specified error occurs. This can be done using PHP die() Function.
Both exceptions and errors are the subclasses of a throwable class. The error implies a problem that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur during runtime and compile time.
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved.
There are three (3) types of fatal errors: Startup fatal error (when the system can't run the code at installation) Compile time fatal error (when a programmer tries to use nonexistent data) Runtime fatal error (happens while the program is running, causing the code to stop working completely)
You can catch purpose of Error
class from this page which describes errors in php
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.
The same description on its own Error
page:
Error is the base class for all internal PHP errors.
So you shouldn't use this class for your user defined exceptions.
The purpose of ErrorException
you can get from this good SO question/answers:
ErrorException is mostly used to convert php error (raised by error_reporting) to Exception
But in php7 you don't need to convert php error to Exception.
So you basically should extend simple Exception
or you can use for standard situations these predefined set of SPL Exceptions (e.g. InvalidArgumentException
, OutOfBoundsException
, BadFunctionCallException
, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With