Open In App

PHP Exception Handling with Multiple Catch Blocks

An exception is an unexpected event that occurs during the execution of a program that breaks the normal flow of instruction. The exceptions arise whenever errors in input data, hardware failures, and programming errors like dividing by zero or trying to access an invalid memory address.

In today's digital world, the application's flow should be maintained properly if any issue occurs. To achieve the application flow maintenance exception handling is a life savior. Exception handling is an important technique, that helps to handle runtime errors (exceptions).

What is the need of Exception Handling?

Exception handling plays an essential role in writing robust code and reliable software. It provides a mechanism for dealing with unexpected situations and errors. It is used to handle errors and other exceptional situations gracefully. It allows the program to respond appropriately rather than crashing or producing incorrect results. Exception handling involves

Single Exception in the Catch Block

Try and Catch blocks are used to monitor the exceptions. If an exception occurs within this block, PHP will stop executing the code in the try block and jump to the corresponding catch block. The catch block contains the code to handle the exception smoothly.

Syntax:

<?php

try {
// Some code...
}
catch (ExceptionType $e) {
// Code to handle the exception
}

?>

Multiple Exceptions in Single Catch Block

PHP 8 introduced a new feature called Multiple Exceptions in Single Catch Block. It provides the option to the developers to catch multiple exceptions in a single catch block using the union-type syntax (|) for exceptions. This feature significantly enhances code readability and reduces redundancy by allowing the handling of various exception types within one catch block.

Syntax:

<?php

try {
// Some code...
}
catch (ExceptionType1 | ExceptionType2 $e) {
// Code to handle the exception
}

?>

Multiple Expectation Implementation (Build-in Exception)

In this Exception, we try to divide a number by zero, so the result is a DivisionByZeroError. By using the multiple exceptions in a single catch block feature, both DivisionByZeroError and InvalidArgumentException (build-in exceptions) are caught by a single catch block. If either of these exceptions occurs within the try block, the code inside the catch block is executed. The catch block catches multiple exception types using the union-type syntax (|).

Example: This example shows the implementation of the multiple Exception.

<?php
     try {
        $result = 10 / 0; // DivisionByZeroError
    } 
    catch (DivisionByZeroError | InvalidArgumentException $e) {
        // Handle both DivisionByZeroError
      // and InvalidArgumentException
        echo "An error occurred: " . $e->getMessage();
    }
?>

Output
Warning: Division by zero in /home/guest/sandbox/Solution.php on line 3

Multiple Expectation Implementation (Custom Exception)

Consider an E-commerce application. We have implemented exception handling for discount percentage validation. There are 3 custom exceptions are defined. They are

While calculating the product's final price, discount percentage value is checked. Whenever the discount percentage value is >100 (percentage should be <=100), DiscountTooHighException will be raised.

In the catch block, both DiscountTooLowException and DiscountTooHighException are caught using the union-type syntax.

Example: This example shows the implementation of the custom multiple Exception.

<?
class InvalidDiscountException extends Exception {}
class DiscountTooLowException extends InvalidDiscountException {}
class DiscountTooHighException extends InvalidDiscountException {}

function calculateFinalPrice($price, $discountPercentage) {
    if ($discountPercentage <= 0) {
        throw new DiscountTooLowException("Discount percentage 
                                          should be greater than 0");
    } 
      elseif ($discountPercentage >= 100) {
        throw new DiscountTooHighException("Discount percentage
                                          should be less than 100");
    } 
    else {
        // Calculate the final price
      // after applying the discount
        $finalPrice = $price * (1 - ($discountPercentage / 100));
        return $finalPrice;
    }
}

try {
    // usage of the calculateFinalPrice
  // function within a try block
    $price = 100;
    $discount = 120; // Invalid discount percentage
    echo "Final price after applying discount: "
      . calculateFinalPrice($price, $discount) . "\n";
} 
catch (DiscountTooLowException | DiscountTooHighException $e) {
    // Handling both DiscountTooLowException
  //  and DiscountTooHighException
    echo "Error: " . $e->getMessage() . "\n";
} 
?>

Output
Error: Discount percentage should be less than 100

Advantages of Multiple Exceptions in Single Catch Block

Conclusion

PHP 8's multiple exceptions in single catch block feature definitely help to improve code readability and reduce redundancy. So While handling real-world applications, the flow of the application should be maintained properly if any issue occurs. So this feature ensures the smooth management of unexpected errors and maintains software stability on the application side and maintains the code readability on the development side.

Article Tags :