PHP Interaction between finally and return


Introduction

There is a peculiar behaviour of finally block when either try block or catch block (or both) contain a return statement. Normally return statement causes control of program go back to calling position. However, in case of a function with try /catch block with return, statements in finally block are executed first before returning.

Example

In following example,div() function has a try - catch - finally construct. The try block without exception returns result of division. In case of exception, catch block returns error message. However, in either case statement in finally block is executed first.

Example

 Live Demo

<?php
function div($x, $y){
   try {
      if ($y==0)
         throw new Exception("Division by 0");
      else
         $res=$x/$y;;
         return $res;
      }
      catch (Exception $e){
         return $e->getMessage();
      }
      finally{
         echo "This block is always executed
";    } } $x=10; $y=0; echo div($x,$y); ?>

Output

Following output is displayed

This block is always executed
Division by 0

Change value of $y to 5. Following output is displayed

This block is always executed
2

Updated on: 18-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements