The source code to demonstrate the finally block in exception handling is given below. The given program is compiled and executed successfully.
<?php
// PHP program to demonstrate the finally block
// in exception handling.
try
{
$A = 10;
$B = 0;
if ($B == 0) throw new Exception("Divide by Zero exception");
$C = $A / $B;
printf("Value of C: %d<br>", $C);
}
catch(Exception $e)
{
printf("Exception: %s<br>", $e->getMessage());
}
finally
{
printf("Finally block executed");
}
?>
Output:
Exception: Divide by Zero exception
Finally block executed
Explanation:
Here, we created used try, catch, and finally block. In the try block, we created two local variables $A, $B that are initialized with 10 and 0 respectively.
if($B==0)
throw new Exception("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, and then finally block gets executed.
The finally block is a block in exception handling that will always be executed whether an exception is generated or not.
Program/Source Code:
The source code to demonstrate the finally block in exception handling is given below. The given program is compiled and executed successfully.
Output:
Explanation:
Here, we created used try, catch, and finally block. In the try block, 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, and then finally block gets executed.
The finally block is a block in exception handling that will always be executed whether an exception is generated or not.