Les exceptions

Sommaire

Note: Voir aussi la classe Exception

PHP a une gestion des exceptions similaire Ă  ce qu'offrent les autres langages de programmation. Une exception peut ĂȘtre lancĂ©e ("throw") et attrapĂ©e ("catch") dans PHP. Le code devra ĂȘtre entourĂ© d'un bloc try pour faciliter la saisie d'une exception potentielle. Chaque try doit avoir au moins un bloc catch ou finally correspondant.

Si une exception est lancée et que la portée courante de la fonction n'a pas de bloc catch, l'exception "remontera" la pile d'appel de la fonction appelante jusqu'à trouver un bloc catch correspondant. Tous les blocs finally rencontrés seront exécutés. Si la pile d'appel est déroulée jusqu'à la portée globale sans rencontrer de bloc catch correspondant, le programme sera terminé avec une erreur fatale sauf si un gestionnaire global d'exception a été défini.

L'objet lancĂ© doit ĂȘtre une instanceof Throwable. Tenter de lancer un objet qui ne l'est pas rĂ©sultera en une erreur fatale Ă©mise par PHP.

À partir de PHP 8.0.0, le mot clĂ© throw est une expression et peut ĂȘtre utilisĂ© dans n'importe quel contexte d'expressions. Dans les versions antĂ©rieures c'Ă©tait une dĂ©claration qui devait ĂȘtre sur sa propre ligne.

catch

Un bloc catch définit comment réagir à une exception qui a été lancée. Un bloc catch définit un ou plusieurs types d'exceptions ou erreurs qu'il peut gérer, et optionnellement une variable dans laquelle assigner l'exception. (Cette variable était requise dans les versions antérieures à PHP 8.0.0) Le premier bloc catch qu'une exception ou erreur lancée rencontre et qui correspond au type de l'objet lancé gérera l'objet.

Plusieurs blocs catch peuvent ĂȘtre utilisĂ©s pour attraper diffĂ©rentes classes d'exceptions. L'exĂ©cution normale (lorsqu'aucune exception n'est lancĂ©e dans le bloc try) continue aprĂšs le dernier bloc catch dĂ©fini dans la sĂ©quence. Les exceptions peuvent ĂȘtre lancĂ©es (throw) ou relancĂ©es dans un bloc catch. Sinon, l'exĂ©cution continuera aprĂšs le bloc catch qui a Ă©tĂ© dĂ©clenchĂ©.

Lorsqu'une exception est lancĂ©e, le code suivant le traitement ne sera pas exĂ©cutĂ© et PHP tentera de trouver le premier bloc catch correspondant. Si une exception n'est pas attrapĂ©e, une erreur fatale issue de PHP sera envoyĂ©e avec un message "Uncaught Exception ..." indiquant que l'exception n'a pu ĂȘtre attrapĂ©e Ă  moins qu'un gestionnaire d'exceptions ne soit dĂ©fini avec la fonction set_exception_handler().

À partir de PHP 7.1.0, un bloc catch peut spĂ©cifier plusieurs exceptions Ă  l'aide du caractĂšre pipe (|). Ceci est utile lorsque diffĂ©rentes exceptions de hiĂ©rarchies de classes diffĂ©rentes sont traitĂ©es de la mĂȘme maniĂšre.

À partir de PHP 8.0.0, le nom de variable pour l'exception attrapĂ©e est optionnel. Si non spĂ©cifiĂ©, le bloc catch sera toujours exĂ©cutĂ© mais n'aura pas accĂšs Ă  l'objet lancĂ©.

finally

Un bloc finally peut aussi ĂȘtre spĂ©cifiĂ© aprĂšs ou Ă  la place des blocs catch. Le code Ă  l'intĂ©rieur du bloc finally sera toujours exĂ©cutĂ© aprĂšs les blocs try et catch, indĂ©pendamment du fait qu'une exception a Ă©tĂ© lancĂ©e, avant de continuer l'exĂ©cution normale.

Une interaction notable est entre un bloc finally et une dĂ©claration return. Si une dĂ©claration return est rencontrĂ©e Ă  l'intĂ©rieur des blocs try ou catch, le bloc finally sera quand mĂȘme exĂ©cutĂ©. De plus, la dĂ©claration return est Ă©valuĂ©e quand elle est rencontrĂ©e, mais le rĂ©sultat sera retournĂ© aprĂšs que le bloc finally soit exĂ©cutĂ©. Additionnellement, si le bloc finally contient aussi une dĂ©claration return la valeur du bloc finally est retournĂ©e.

Une autre interaction notable est entre une exception lancée dans un bloc try, et une exception lancée dans un bloc finally. Si une exception est lancée dans les deux blocs, alors, l'exception lancée dans le bloc finally sera celle qui sera propagée, et l'exception lancée dans le bloc try sera utilisée comme exception précédente.

Gestionnaire d'exceptions global

Si une exception est autorisĂ©e Ă  remonter jusqu'Ă  la portĂ©e globale, elle peut ĂȘtre attrapĂ©e par un gestionnaire d'exceptions global s'il a Ă©tĂ© dĂ©fini. La fonction set_exception_handler() peut dĂ©finir une fonction qui sera appelĂ©e Ă  la place d'un bloc catch si aucun autre bloc n'est invoquĂ©. L'effet est essentiellement identique Ă  entourer le programme entier dans un bloc try-catch avec cette fonction en tant que catch.

Notes

Note:

Les fonctions internes de PHP utilisent principalement l' Error reporting, seules les extensions orientĂ©es objet modernes utilisent les exceptions. Quoi qu'il en soit, des erreurs peuvent facilement ĂȘtre traduites en exceptions avec ErrorException. Cependant, cette technique ne fonctionne que pour les erreurs non fatales.

Exemple #1 Convertir l'error reporting en exceptions

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new
ErrorException($message, 0, $severity, $filename, $lineno);
}

set_error_handler('exceptions_error_handler');

Exemples

Exemple #2 Lancer une exception

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division par zéro.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Exception reçue : ', $e->getMessage(), "\n";
}

// On continue l'exécution
echo "Bonjour le monde !\n";

L'exemple ci-dessus va afficher :

0.2
Exception reçue : Division par zéro.
Bonjour le monde !

Exemple #3 Gestion de l'exception avec un bloc finally

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division par zéro.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
} catch (
Exception $e) {
echo
'Exception reçue : ', $e->getMessage(), "\n";
} finally {
echo
"PremiĂšre fin.\n";
}

try {
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Exception reçue : ', $e->getMessage(), "\n";
} finally {
echo
"Seconde fin.\n";
}

// On continue l'exécution
echo "Bonjour le monde !\n";

L'exemple ci-dessus va afficher :

0.2
PremiĂšre fin.
Exception reçue : Division par zéro.
Seconde fin.
Bonjour le monde !

Exemple #4 Interaction entre le bloc finally et return

<?php

function test() {
try {
throw new
Exception('foo');
} catch (
Exception $e) {
return
'catch';
} finally {
return
'finally';
}
}

echo
test();

L'exemple ci-dessus va afficher :

finally

Exemple #5 Exception imbriquée

<?php

class MyException extends Exception { }

class
Test {
public function
testing() {
try {
try {
throw new
MyException('foo!');
} catch (
MyException $e) {
// on la relance
throw $e;
}
} catch (
Exception $e) {
var_dump($e->getMessage());
}
}
}

$foo = new Test;
$foo->testing();

L'exemple ci-dessus va afficher :

string(4) "foo!"

Exemple #6 Gestion des exceptions de capture multiple

<?php

class MyException extends Exception { }

class
MyOtherException extends Exception { }

class
Test {
public function
testing() {
try {
throw new
MyException();
} catch (
MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}

$foo = new Test;
$foo->testing();

L'exemple ci-dessus va afficher :

string(11) "MyException"

Exemple #7 Omettre la variable attrapée

Seulement permis dans PHP 8.0.0 et ultérieur.

<?php

class SpecificException extends Exception {}

function
test() {
throw new
SpecificException('Oopsie');
}

try {
test();
} catch (
SpecificException) {
print
"Une SpecificException a été levée, mais les détails ne nous intéressent pas.";
}

L'exemple ci-dessus va afficher :

Une SpecificException a été levée, mais les détails ne nous intéressent pas.

Exemple #8 Throw en tant qu'expression

Seulement permis dans PHP 8.0.0 et ultérieur.

<?php

function test() {
do_something_risky() or throw new Exception("Cela n'a pas fonctionné");
}

function
do_something_risky() {
return
false; // Simuler un échec
}

try {
test();
} catch (
Exception $e) {
print
$e->getMessage();
}

L'exemple ci-dessus va afficher :

Cela n'a pas fonctionné

Exemple #9 Exception dans try et dans finally

<?php

try {
try {
throw new
Exception(message: 'Third', previous: new Exception('Fourth'));
} finally {
throw new
Exception(message: 'First', previous: new Exception('Second'));
}
} catch (
Exception $e) {
var_dump(
$e->getMessage(),
$e->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getPrevious()->getMessage(),
);
}

L'exemple ci-dessus va afficher :

string(5) "First"
string(6) "Second"
string(5) "Third"
string(6) "Fourth"
add a note

User Contributed Notes 13 notes

up
130
ask at nilpo dot com ¶
17 years ago
If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message 
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace
    
    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($message = null, $code = 0);
}

abstract class CustomException extends Exception implements IException
{
    protected $message = 'Unknown exception';     // Exception message
    private   $string;                            // Unknown
    protected $code    = 0;                       // User-defined exception code
    protected $file;                              // Source filename of exception
    protected $line;                              // Source line of exception
    private   $trace;                             // Unknown

    public function __construct($message = null, $code = 0)
    {
        if (!$message) {
            throw new $this('Unknown '. get_class($this));
        }
        parent::__construct($message, $code);
    }
    
    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new TestException();
    }
    catch (TestException $e) {
        echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (Exception $e) {
        echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo '<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
up
78
Johan ¶
15 years ago
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start();
try {
    /*contains all page logic 
    and throws error if needed*/
    ...
} catch (Exception $e) {
  ob_end_clean();
  displayErrorPage($e->getMessage());
}
?>
up
33
Edu ¶
12 years ago
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
        try {
                throw new \Exception("Hello");
        } catch(\Exception $e) {
                echo $e->getMessage()." catch in\n";
                throw $e;
        } finally {
                echo $e->getMessage()." finally \n";
                throw new \Exception("Bye");
        }
} catch (\Exception $e) {
        echo $e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally 
Bye catch out
up
26
Shot (Piotr Szotkowski) ¶
17 years ago
‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception 
” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
up
9
tianyiw at vip dot qq dot com ¶
2 years ago
Easy to understand `finally`.
<?php
try {
    try {
        echo "before\n";
        1 / 0;
        echo "after\n";
    } finally {
        echo "finally\n";
    }
} catch (\Throwable) {
    echo "exception\n";
}
?>
# Print:
before
finally
exception
up
15
christof+php[AT]insypro.com ¶
8 years ago
In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php 
    set_error_handler(function($errno, $errstr, $errfile, $errline){
            if($errno === E_WARNING){
                // make it more serious than a warning so it can be caught
                trigger_error($errstr, E_ERROR);
                return true;
            } else {
                // fallback to default php error handler
                return false;
            }
    });

    try {
            // code that might result in a E_WARNING
    } catch(Exception $e){
            // code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
    } finally {
            restore_error_handler();
    }
?>
up
16
daviddlowe dot flimm at gmail dot com ¶
8 years ago
Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?php

try {
    throw new Error( "foobar" );
    // or:
    // throw new Exception( "foobar" );
}
catch (Throwable $e) {
    var_export( $e );
}

?>
up
18
Simo ¶
11 years ago
#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.
up
20
telefoontoestel at nospam dot org ¶
11 years ago
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block. 

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
} finally {
    echo "finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
    exit(1);
} finally {
    echo "finally block<br />";
}

// try block
// catch block
?>
up
6
jlherren ¶
2 years ago
As noted elsewhere, throwing an exception from the `finally` block will replace a previously thrown exception. But the original exception is magically available from the new exception's `getPrevious()`.

<?php
try {
    try {
        throw new RuntimeException('Exception A');
    } finally {
        throw new RuntimeException('Exception B');
    }
}
catch (Throwable $exception) {
    echo $exception->getMessage(), "\n";
    // 'previous' is magically available!
    echo $exception->getPrevious()->getMessage(), "\n";
}
?>

Will print:

Exception B
Exception A
up
10
mlaopane at gmail dot com ¶
8 years ago
<?php

/**
 * You can catch exceptions thrown in a deep level function
 */

function employee()
{
    throw new \Exception("I am just an employee !");
}

function manager()
{
    employee();
}

function boss()
{
    try {
        manager();
    } catch (\Exception $e) {
        echo $e->getMessage();
    }
}

boss(); // output: "I am just an employee !"
up
12
Tom Polomsk ¶
11 years ago
Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.
up
12
Sawsan ¶
14 years ago
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name = "Name";

//check if the name contains only letters, and does not contain the word name

try
   {
   try
     {
      if (preg_match('/[^a-z]/i', $name)) 
       {
           throw new Exception("$name contains character other than a-z A-Z");
       }   
       if(strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new Exception("$name contains the word name");
       }
       echo "The Name is valid";
     }
   catch(Exception $e)
     {
     throw new Exception("insert name again",0,$e);
     }
   }
 
catch (Exception $e)
   {
   if ($e->getPrevious())
   {
    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo "The Exception is: ".$e->getMessage()."<br/>";
   }

 ?>