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.
Program/Source Code:
The source code to demonstrate the use of multiple catch blocks is given below. The given program is compiled and executed successfully.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer