update page now
PHP 8.5.2 Released!

Erros no PHP 7

O PHP 7 modificou como a maioria dos erros são reportados pelo PHP. Em vez de reportá-los através do mecanismo tradicional de reporte de erros utilizado pelo PHP 5, a maioria dos erros, agora são reportados lançando exceções Error

Assim como exceções normais, as exceções Error serão elevadas até alcançarem o primeiro bloco catch correspondente. Se não existir nenhum bloco correspondente, qualquer manipulador de exceção padrão instalado com a função set_exception_handler() será chamado, e se não existir nenhum manipulador padrão de exceção, a exceção será convertida em um erro fatal e será tratada como um erro tradicional.

Já que a hierarquia de Error não herda de Exception, códigos que utilizam blocos catch (Exception $e) { ... } para manipular exceções que não foram capturadas no PHP 5, descobrirão que esses Errors não são capturados por estes blocos. Um bloco catch (Error $e) { ... }, ou um manipulador definido com a função set_exception_handler() será necessário.

add a note

User Contributed Notes 5 notes

up
107
hungry dot rahly at gmail dot com
10 years ago
You can catch both exceptions and errors by catching(Throwable)
up
63
demis dot palma at tiscali dot it
9 years ago
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
}
up
4
diogoca at gmail dot com
6 years ago
<?php

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

try {
    echo $x; # notice, handled on callable
    pg_exec(null, null); # 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
up
5
ryan dot jentzsch@{gmail} dot com
8 years ago
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/
up
4
lubaev dot ka at gmail dot com
9 years ago
php 7.1

try {
   // Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
   // pass
}
To Top