
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements