Maison  >  Article  >  développement back-end  >  Qu’est-ce que la gestion des exceptions en PHP ?

Qu’est-ce que la gestion des exceptions en PHP ?

王林
王林avant
2023-09-17 08:45:10926parcourir

Qu’est-ce que la gestion des exceptions en PHP ?

Les exceptions sont des problèmes qui surviennent lors de l'exécution du programme. Lors de l'exécution du programme, lorsqu'une exception se produit, le code suivant l'instruction ne sera pas exécuté et PHP tentera de trouver le premier bloc catch correspondant. Si l'exception n'est pas interceptée, une erreur fatale PHP est émise avec "Uncaught Exception" affiché. La traduction chinoise de

Syntax

   try {
      print "this is our try block";
      throw new Exception();
      }catch (Exception $e) {
         print "something went wrong, caught yah! n";
      }finally {
         print "this part is always executed";
      }

Example

est :

Example

<?php
   function printdata($data) {
      try {
         //If var is six then only if will be executed
         if($data == 6) {
         // If var is zero then only exception is thrown
         throw new Exception(&#39;Number is six.&#39;);
            echo "</p><p> After throw (It will never be executed)";
         }
      }
      // When Exception has been thrown by try block
         catch(Exception $e){
            echo "</p><p> Exception Caught", $e->getMessage();
         }
      //this block code will always executed.
         finally{
            echo "</p><p> Final block will be always executed";
         }
   }
   // Exception will not be rised here
      printdata(0);
      // Exception will be rised
      printdata(6);

?>

Output

Final block will be always executed
Exception CaughtNumber is six.
Final block will be always executed

Remarque

Pour gérer les exceptions, le code du programme doit être à l'intérieur d'un bloc try. Chaque tentative doit avoir au moins un bloc catch correspondant. Plusieurs blocs catch peuvent être utilisés pour intercepter différentes catégories d’exceptions.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer