Wednesday, 15 October 2025

Exception Handling in PHP

Exception handling is a powerful mechanism in PHP, which is used to handle runtime errors (runtime errors are called exceptions). 

The main purpose of using exception handling is to maintain the normal execution of the application.

Exception

An exception is an unexpected outcome of a program, which can be handled by the program itself.

Basically, an exception disrupts the normal flow of the program. 

But it is different from an error because an exception can be handled, whereas an error cannot be handled by the program itself.


Need for Exception Handlers

Exception handling is required when an exception interrupts the normal execution of the program or application.

PHP provides a powerful mechanism for exception handling. 

It can be used to handle runtime errors such as IOException, SQLException, ClassNotFoundException, and more. 

A most popular example of exception handling is the divide by zero exception, which is an arithmetic exception.



Try block

The try block contains the code that may have an exception or where an exception can arise. 
When an exception occurs inside the try block during runtime of code, it is caught and resolved in catch block.
 The try block must be followed by a catch or finally block. 
A try block can be followed by minimum one and any number of catch blocks.

Catch block

The catch block contains the code that executes when a specified exception is thrown. 
It is always used with a try block, not alone. 
When an exception occurs, PHP finds the matching catch block.

Throw block

t is a keyword used to throw an exception. 
It also helps to list all the exceptions that a function throws but does not handle itself.
Remember that each throw must have at least one "catch".

Finally block
The finally block contains code, which is used for clean-up activity in PHP.
Basically, it executes the essential code of the program.

Exception outcome

The current state of the code is saved.
The execution of the code is switched to a predefined exception handler function.
Depending on the situation, 
  • the handler can halt the execution of the program, 
  • resume the execution from the saved code state, 
  • or continue the execution of the code from another location in the code.

//Script using Exception Handler

<?php  
//user-defined function with an exception  
function checkNumber($num) {  
   if($num>=1) {  
     //throw an exception  
     throw new Exception("Value must be less than 1");  
   }  
   return true;  
}  
  
//trigger an exception in a "try" block  
try {  
   checkNumber(5);  
   //If the exception throws, the below text will not be displayed  
   echo 'If you see this text, the passed value is less than 1';  
}  
  
//catch exception  
catch (Exception $e) {  
   echo 'Exception Message: ' .$e->getMessage();  
}  
?>