Sunday 13 June 2021

Php: finally block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Finally block mainly used to perform clean-up operation like closing file streams, flushing the data etc.,

 

A try block must associate with at least one catch or finally block.

 

Example

try{
    div(10,0);
}catch(LogicException $e){
    echo "Exception occurred: ". $e->getMessage();
}finally{
    echo "\ni will execute always";
}

 

Find the below working application.

 

finally_block_demo.php

 

#!/usr/bin/php

<?php 

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

   try{
    div(10,0);
   }catch(LogicException $e){
       echo "Exception occurred: ". $e->getMessage();
   }finally{
    echo "\ni will execute always";
   }
?>

 

Output

$./finally_block_demo.php 

Exception occurred: Division by zero
i will execute always

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment