Home  >  Article  >  Backend Development  >  What is exception handling in PHP?

What is exception handling in PHP?

王林
王林forward
2023-09-17 08:45:10950browse

What is exception handling in PHP?

Exceptions are problems that occur during program execution. During program execution, when an exception occurs, the code following the statement will not be executed and PHP will try to find the first matching catch block. If the exception is not caught, a PHP fatal error is issued with "Uncaught Exception" displayed.

Grammar

   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

Chinese translation is:

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

Note

To To handle exceptions, program code must be located within a try block. Each attempt must have at least one corresponding catch block. Multiple catch blocks can be used to catch different categories of exceptions.

The above is the detailed content of What is exception handling in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete