What is Exception Handling in PHP ?

PHPProgrammingServer Side Programming

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”.


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


   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 "
After throw (It will never be executed)";          }       }       // When Exception has been thrown by try block          catch(Exception $e){             echo "
Exception Caught", $e->getMessage();          }       //this block code will always executed.          finally{             echo "
Final block will be always executed";          }    }    // Exception will not be rised here       printdata(0);       // Exception will be rised       printdata(6); ?>


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


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.

Updated on 29-Jun-2020 12:05:32