What is exception handling in PHP?

王林
Release: 2023-09-17 08:46:01
forward
922 people have browsed it

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";
      }
Copy after login

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);

?>
Copy after login

Output

Final block will be always executed
Exception CaughtNumber is six.
Final block will be always executed
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!