PHP program to demonstrate the use of multiple catch blocks

Here, we are going to demonstrate the use of multiple catch blocks in PHP.
Submitted by Nidhi, on November 22, 2020 [Last updated : March 13, 2023]

Multiple Catch Blocks Example

Here, we will demonstrate the multiple catch blocks, here we will create a user define exception class and also used a predefined exception class.

PHP code to demonstrate the example of multiple catch blocks

The source code to demonstrate the use of multiple catch blocks is given below. The given program is compiled and executed successfully.

<?php
// PHP program to demonstrate the use of multiple catch blocks.
class MyException extends Exception
{
}

try
{

    $A = 10;
    $B = - 1;

    if ($B == 0) throw new MyException("Divide by Zero exception");
    if ($B == - 1) throw new Exception("Negative exception");
    $C = $A / $B;
    printf("Value of C: %d<br>", $C);

}
catch(MyException $e)
{
    printf("Exception: %s<br>", $e->getMessage());
}
catch(Exception $e)
{
    printf("Exception: %s<br>", $e->getMessage());
}

?>

Output

Exception: Negative exception

Explanation

Here, we created a user-defined exception class that inherits the Exception class. In the try block, we have thrown exception based on the conditions for divide by zero and negative value exception, and we defined two catch blocks for the different exceptions.

The above program will throw an exception for the negative value that will be caught by the appropriate catch block and print an appropriate message on the webpage.

PHP Exception Handling Programs »





All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.