Computer >> Computer tutorials >  >> Programming >> PHP

What is Exception Handling in PHP ?


An exception is a problem that arised during the execution of a program. During the execution of a program when an exception occurs, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception”.

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

<?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('Number is six.');
            echo "\n After throw (It will never be executed)";
         }
      }
      // When Exception has been thrown by try block
         catch(Exception $e){
            echo "\n Exception Caught", $e->getMessage();
         }
      //this block code will always executed.
         finally{
            echo "\n 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 handle exceptions, program code must inside a try block. Each try must have at least one respective catch block. Multiple catch blocks can be used to catch different classes of exceptions.