In PHP 7 the base interface for any object that can be thrown is Throwable. We also have an Error base class for all internal PHP errors. But why then I can't catch errors like:
a)
try {
$file = fopen('not_exist_file', 'r');
} catch (\Error $e) {
echo 'Cannot open a file';
}
Expected result: 'Cannot open a file'
Actual result: PHP Warning: fopen(not_exist_file): failed to open stream: No such file or directory
b)
try {
$result = 10 / 0;
} catch(\DivisionByZeroError $e){
echo 'Catch DivisionByZeroError';
} catch (\Throwable $e) {
echo 'Catch Throwable';
}
Expected result: 'Catch DivisionByZeroError'
Actual result: PHP Warning: Division by zero in ..
c)
try {
trigger_error('User error');
} catch(\Error $e) {
echo 'Catch error';
} catch (\Throwable $e) {
echo 'Catch throwable';
}
Expected result: 'Catch error'
Actual result: PHP Notice: User error in ..
My PHP version 7.1.1 (cli)
Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }
Try, throw and catch Proper exception code should include: try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal.
The errors you listed are not caught because they are not thrown. They are not exceptions but traditional errors that are triggered by the PHP code since its very beginning, years before the exceptions and OOP were introduced in the language.
You can, however, install an error handler that can handle the errors by creating and throwing ErrorException
objects for them.
The documentation of the ErrorException
class includes a simple example of how to do it.
Not all PHP functions throw exceptions. Exceptions are an OO concept, whereas these are plain old PHP functions.
Always check the manual to see what the return is result!
http://php.net/manual/en/function.fopen.php
http://php.net/manual/en/function.trigger-error.php
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