The finally Command
The finally
block is used together with try
and catch
constructs for exception handling. The code inside finally will execute in any case - both upon successful execution of the try block and when an exception occurs.
Syntax
try {
// Code that may throw an exception
} catch (Exception $e) {
// Exception handling
} finally {
// Code that will always execute
}
Example
Example with successful code execution:
<?php
try {
$res = 10 / 2;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Code execution result:
Result: 5
This will always execute
Example
Example with exception handling:
<?php
try {
$res = 10 / 0;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Code execution result:
Exception: Division by zero
This will always execute
Example
Using finally to free resources:
<?php
$file = fopen("example.txt", "r");
try {
// Working with the file
if ($file) {
echo "File opened successfully\n";
}
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
if ($file) {
fclose($file);
echo "File closed in finally block\n";
}
}
?>
Code execution result:
File opened successfully
File closed in finally block