PHP Exception Handling with finally


Introduction

Code in finally block will always get executed whether there is an exception in ry block or not. This block appears either after catch block or instead of catch block.

catch and finally block

In following example, both catch and finally blocks are given. If execption occurs in try block, code in both is executed. If there is no exception, only finally block is executed.

Example

 Live Demo

<?php
function div($x, $y) {
   if (!$y) {
      throw new Exception('Division by zero.');
   }
   return $x/$y;
}
try {
   echo div(10,0) . "
"; } catch (Exception $e) {    echo 'Caught exception: ', $e->getMessage(), "
"; } finally{    echo "This block is always executed
"; } // Continue execution echo "Execution continues
"; ?>

Output

Following output is displayed

Caught exception: Division by zero.
This block is always executed
Execution continues

change statement in try block so that no exception occurs

Example

 Live Demo

<?php
function div($x, $y) {
   if (!$y) {
      throw new Exception('Division by zero.');
   }
   return $x/$y;
}
try {
   echo div(10,5) . "
"; } catch (Exception $e) {    echo 'Caught exception: ', $e->getMessage(), "
"; } finally{    echo "This block is always executed
"; } // Continue execution echo "Execution continues
"; ?>

Output

Following output is displayed

2
This block is always executed
Execution continues

finally block only

Following example has two try blocks. One of them has only finally block. Its try block calls div function which throws an exception

Example

 Live Demo

<?php
function div($x, $y){
   try{
      if (!$y) {
         throw new Exception('Division by zero.');
      }
      return $x/$y;
   }
   catch (Exception $e) {
      echo 'Caught exception: ', $e->getMessage(), "
";    } } try {    echo div(10,0) . "
"; } finally{    echo "This block is always executed
"; } // Continue execution echo "Execution continues
"; ?>

Output

Following output is displayed

Caught exception: Division by zero.

This block is always executed
Execution continues

Updated on: 18-Sep-2020

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements