How to handle Exception in PHP?

In this article, we will learn how we can handle errors and exceptions in PHP.

First of all, we have to understand what really an exception is. After that, we will learn how to do Exception handling in PHP programming language.

What is an exception?

  • An exception is an unexpected outcome in the script that can interrupt the flow of the script.
  • It may be a predefined exception or user-defined exception.

Example:-

This example creates a user-defined exception,

<?php 

try 
 { 
  throw new Exception("This is a exception.Try to solve the exception."); //throw an userdefined exception 
 } 
catch (Exception $e) 
 {
  echo $e->getMessage(); 
  die(); 
 }
 
?>

output:-

This is a exception.Try to solve the exception.

Why handle the exception?

  • Handling exception is required for showing the correct output rather than showing any garbage value or any interruption of the script.
  • An exception is always meant to change the flow of the script. So handling the exception is highly required to maintain the normal flow of the script.

How to handle an exception in PHP

Exception Handling in PHP involves 3 steps:

  • Try − The code containing error or the code that is suspected to have an error should be kept inside try block.  Every try block throws an error to a particular catch block.
  • Throw − It throws a predefined as well as a user-defined error to the catch block. It is placed under the try block.
  • Catch − This block involves the action regarding an error. It creates the object of predefined error class to match with the type of error thrown by the try block. Multiple catch blocks can be present inside a program.

Program of exception handling in PHP

Let us illustrate the workings of the above steps by taking a small user-defined exception example:

<?php

  function division($dividend, $divisor)
{
  if($divisor == 0)
         throw new Exception('Division by zero.');    // Throw exception if divisor is zero

  else
      {
          $quotient = $dividend / $divisor;
          echo "<p>$dividend / $divisor = $quotient</p>";
      }
}
    
division(15, 0);

?>

output:-

Fatal error: Uncaught Exception at line 5

The absence of try and catch block is the main reason for the error. Let us handle the exception in a proper way as follows:

<?php
function division($dividend, $divisor)
{
    if($divisor == 0)
        throw new Exception('Division by zero.');	    // Throw exception if divisor is zero  
   else{
          $quotient = $dividend / $divisor;
          echo "<p>$dividend / $divisor = $quotient</p>";
           }
}
try
{
    division(15, 0);
}
 catch(Exception $e) 		  // Handle the exception
{
    echo "<p>Caught exception: " . $e->getMessage() . "</p>";
}
?>

output:-

Caught exception: Division by zero.

What is Finally Block?

  • Execution of Finally block starts along with try and catch block.
  • It always comes into the finally block, no matter any catch block catches the error or not.

Example:-

<?php
function division($dividend, $divisor)
{
    if($divisor == 0)
        throw new Exception('Division by zero.');	    // Throw exception if divisor is zero  
   else{
          $quotient = $dividend / $divisor;
          echo "<p>$dividend / $divisor = $quotient</p>";
           }
}
try
{
    division(15, 0);
}
 catch(Exception $e) 		  // Handle the exception
{
    echo "<p>Caught exception: " . $e->getMessage() . "</p>";
}
finally {
  echo "<p>In finally block</p>";//it'll always be executed
}
?>

output:-

Caught exception: Division by zero.

In finally block

In this way, we can handle an exception using PHP. If you have any doubts about this topic then comment below.

See also,

Leave a Reply

Your email address will not be published. Required fields are marked *