PHP 5.1 has introduced ErrorException. The constructor of the two functions differs
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
Is there a difference when to use either?
I suspect that the above use case is incorrect:
<?php
class Data {
public function save () {
try {
// do something
} catch (\PDOException $e) {
if ($e->getCode() == '23000') {
throw new Data_Exception('Foo Bar', $e);
}
throw $e
}
}
}
class Data_Exception extends ErrorException /* This should not be using ErrorException */ {}
It isn't documented well, but it appears that ErrorException
is designed to be used explicitly from the custom error handler as in the original example, http://php.net/manual/en/class.errorexception.php.
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
Summary of Differences: 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.
An Error "indicates serious problems that a reasonable application should not try to catch." An Exception "indicates conditions that a reasonable application might want to catch." Error along with RuntimeException & their subclasses are unchecked exceptions.
An error is when something wrong or invalid happens in the code. It can cause a memory error, it is something that should never happen and can't be treated. Whereas an exception throws something when certain conditions are met in the code. It may not correspond to a real error.
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)
ErrorException
is mostly used to convert php error (raised by error_reporting) to Exception
.
You should avoid using directly Exception
which is too wide. Subclass it with specific Exception
or use predefined SPL Exception
To follow your edit : Yes extends Exception
rather than ErrorException
.
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