Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP 7 doesn't catch some errors? [duplicate]

Tags:

php

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)

like image 961
Sauron918 Avatar asked Jul 17 '18 13:07

Sauron918


People also ask

How can I catch exception in PHP?

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 ) { // ... }

Can we use try without catch in PHP?

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.


2 Answers

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.

like image 104
axiac Avatar answered Sep 30 '22 12:09

axiac


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

like image 22
delboy1978uk Avatar answered Sep 30 '22 10:09

delboy1978uk