Here, we will create a user-defined class DivideByZeroException that inherits the Exception class to handle the divide by zero situation using the PHP program.
The source code to create DivideByZeroException class using exception handling is given below. The given program is compiled and executed successfully.
<?php
// PHP program to create DivideByZeroException class.
class DivideByZeroException extends Exception
{
}
try
{
$A = 10;
$B = 0;
if ($B == 0) throw new DivideByZeroException("Divide by Zero exception");
$C = $A / $B;
printf("Value of C: %d<br>", $C);
}
catch(DivideByZeroException $e)
{
printf("Exception: %s", $e->getMessage());
}
?>
Output:
Exception: Divide by Zero exception
Explanation:
Here, we created a class DivideByZeroException that inherits the predefined class Exception. Here, we created two local variables $A, $B that are initialized with 10 and 0 respectively.
if($B==0)
throw new DivideByZeroException ("Divide by Zero exception");
Here, we check the condition, if the value of $B is 0 then it will throw an exception using the throw keyword that will be caught by catch block and print specified message on the webpage.
Program/Source Code:
The source code to create DivideByZeroException class using exception handling is given below. The given program is compiled and executed successfully.
Output:
Explanation:
Here, we created a class DivideByZeroException that inherits the predefined class Exception. Here, we created two local variables $A, $B that are initialized with 10 and 0 respectively.
Here, we check the condition, if the value of $B is 0 then it will throw an exception using the throw keyword that will be caught by catch block and print specified message on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer