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) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } finally{ echo "This block is always executed\n"; } // Continue execution echo "Execution continues\n"; ?>
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) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } finally{ echo "This block is always executed\n"; } // Continue execution echo "Execution continues\n"; ?>
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(), "\n"; } } try { echo div(10,0) . "\n"; } finally{ echo "This block is always executed\n"; } // Continue execution echo "Execution continues\n"; ?>
Output
Following output is displayed
Caught exception: Division by zero. This block is always executed Execution continues