CakeFest 2024: The Official CakePHP Conference

Les Erreurs en PHP 7

PHP 7 modifie la facon dont la plupart des erreurs sont signalées en PHP. Au lieu d'utiliser le mécanisme traditionnel de gestion d'erreur de PHP 5, la plupart des erreurs sont maintenant signalées en lançant une exception Error

Comme pour les exceptions normales, ces exceptions Error remonteront jusqu'à ce qu'elles atteignent le premier bloc d'attrape catch correspondant. S'il n'y a pas de bloc correspondant, le gestionnaire d'exception défini par défaut avec la fonction set_exception_handler() sera appelé. Et s'il n'y a pas de gestionnaire d'exception par défaut, alors l'exception sera convertie en erreur fatale et sera traitée comme une erreur traditionnelle.

Comme la hiérarchie des classes Error n'hérite pas d'Exception, le code qui utilise les blocs d'attrape catch (Exception $e) { ... } pour traiter les exceptions non-interceptées en PHP 5 n'interceptera pas ces exceptions Errors. Il faudra donc utiliser soit un bloc catch (Error $e) { ... }, soit un gestionnaire d'exception défini avec set_exception_handler().

add a note

User Contributed Notes 5 notes

up
107
hungry dot rahly at gmail dot com
8 years ago
You can catch both exceptions and errors by catching(Throwable)
up
65
demis dot palma at tiscali dot it
7 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
5
ryan dot jentzsch@{gmail} dot com
6 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
2
diogoca at gmail dot com
4 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
4
lubaev dot ka at gmail dot com
7 years ago
php 7.1

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