
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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
<?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
- Related Articles
- Differentiate between Interface design and Interaction design
- PHP Exception Handling with finally
- Difference Between Final, Finally and Finalize in Java
- PHP return Statement
- What is the difference between final, finally and finalize() in Java?
- Return all dates between two dates in an array in PHP
- Parent-Child Interaction Therapy: Meaning And Application
- PHP Return by Reference
- Meaning of Individual and Group Interaction in Psychology
- Can we write any statements between try, catch and finally blocks in Java?
- Can we have a return statement in the catch or, finally blocks in Java?
- Will a finally block execute after a return statement in a method in Java?
- final, finally and finalize in Java
- final, finally and finalize in C#
- Difference between Python and PHP.

Advertisements