Errors in PHP 7

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.

As with normal exceptions, these Error exceptions will bubble up until they reach the first matching catch block. If there are no matching blocks, then any default exception handler installed with set_exception_handler() will be called, and if there is no default exception handler, then the exception will be converted to a fatal error and will be handled like a traditional error.

As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.

Error hierarchy

  • Throwable
    • Error
      • ArithmeticError
        • DivisionByZeroError
      • AssertionError
      • ParseError
      • TypeError
    • Exception
      • ...

Коментарии

You can catch both exceptions and errors by catching(Throwable)
2016-01-08 02:26:28
http://php5.kiev.ua/manual/ru/language.errors.php7.html
Throwable does not work on PHP 5.x.

To catch both exceptions and errors in PHP 5.x and 7, add a catch block for Exception AFTER catching Throwable first.
Once PHP 5.x support is no longer needed, the block catching Exception can be removed.

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
   // Executed only in PHP 5, will not be reached in PHP 7
}
2016-07-26 14:04:28
http://php5.kiev.ua/manual/ru/language.errors.php7.html
php 7.1

try {
   // Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
   // pass
}
2016-12-01 19:16:22
http://php5.kiev.ua/manual/ru/language.errors.php7.html
An excellent blog post on the difference between exceptions, throwables and how PHP 7 handles these can be found here: https://trowski.com/2015/06/24/throwable-exceptions-and-errors-in-php7/
2017-08-09 00:41:36
http://php5.kiev.ua/manual/ru/language.errors.php7.html
<?php

set_error_handler
(function(int $numberstring $message) {
   echo 
"Handler captured error $number: '$message'" PHP_EOL  ;
});

try {
    echo 
$x# notice, handled on callable
   
pg_exec(nullnull); # warning, handled on callable
   
fho(); # fatal error, stop running and catched
} catch (Throwable $e) {
    echo 
"Captured Throwable: " $e->getMessage() . PHP_EOL;
}

?>

set_error_handler will also works without try and catch
2019-11-24 16:38:15
http://php5.kiev.ua/manual/ru/language.errors.php7.html

    Поддержать сайт на родительском проекте КГБ