- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
<?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
<?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
<?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
Advertisements