6

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)

AymDev
  • 6,626
  • 4
  • 29
  • 52
Sauron918
  • 93
  • 2
  • 5
  • 2
    _“But why then I can't catch errors like […]”_ - _because_ they are simple errors. You can only _catch_ what someone _threw_ in the first place, and fopen or a division by zero simply don’t do anything like that. – CBroe Jul 17 '18 at 14:00
  • 1
    The errors you listed are not caught because they are not thrown. They are not exceptions but traditional errors that are [triggered](http://php.net/manual/en/function.trigger-error.php) by the PHP code since its very beginning, years before the exceptions and OOP were introduced in the language. – axiac Jul 17 '18 at 14:05
  • To "catch" these language level errors you need to set a custom error handler - http://php.net/manual/en/function.set-error-handler.php – Bananaapple Jul 17 '18 at 14:09
  • 1
    One reason they are WARNING and not ERRORS [See this for explanation](https://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning) – RiggsFolly Jul 17 '18 at 14:11

2 Answers2

5

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.

axiac
  • 68,258
  • 9
  • 99
  • 134
2

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

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39