Open In App

PHP Exception Handling with Multiple Catch Blocks

Last Updated : 02 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Detecting when an exception occurs (Try block).
  • How to handle it (Catch block).
  • How to recover from it.

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
<?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

  • InvalidDiscountException
  • DiscountTooLowException
  • DiscountTooHighException.

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.

  • Here discount percentage is given as 120 which is >100. So The DiscountTooHighException is thrown and that is caught by the catch block.
  • Similarly, if the discountPercentage value is -1 that is less than 0, so DiscountTooLowException is raised and caught by the catch block.

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.

PHP
<?
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

  • Easy Maintenance: When the error handling logic needs to change, we can easily update one place rather than in multiple catch blocks.
  • Increase Readability: This feature reduces the amount of repeated error-handling code, So developers can focus more on the business logic rather than the error-handling mechanisms.
  • Improved Performance: Generally a single catch block takes less time and faster performance compared to multiple catch blocks.

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads