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