0
0
PHPprogramming~5 mins

Finally block behavior in PHP

Choose your learning style9 modes available
Introduction

The finally block lets you run code that must happen no matter what, even if there was an error or the program returned early.

Closing a file or database connection after trying to read or write data.
Releasing resources like locks or memory after a task finishes.
Ensuring cleanup code runs even if an error happens in your program.
Logging information about what happened, regardless of success or failure.
Syntax
PHP
<?php
try {
    // code that might cause an error
} catch (Exception $e) {
    // code to handle the error
} finally {
    // code that always runs
}
?>

The finally block runs after try and catch, no matter what.

If there is no catch block, finally still runs after try.

Examples
This runs the try code and then the finally code, even without a catch.
PHP
<?php
try {
    echo "Start\n";
} finally {
    echo "Always runs\n";
}
?>
This catches an error and then runs the finally block.
PHP
<?php
try {
    throw new Exception("Error!");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "\n";
} finally {
    echo "Cleanup code\n";
}
?>
The finally block runs even if the try block returns early.
PHP
<?php
try {
    return "From try";
} finally {
    echo "Finally runs even with return\n";
}
?>
Sample Program

This program shows that the finally block runs even if the catch block returns a value.

PHP
<?php
function testFinally() {
    try {
        echo "Trying...\n";
        throw new Exception("Oops");
    } catch (Exception $e) {
        echo "Caught exception: " . $e->getMessage() . "\n";
        return "Returned from catch";
    } finally {
        echo "Finally block runs no matter what\n";
    }
}

$result = testFinally();
echo "Result: $result\n";
?>
OutputSuccess
Important Notes

The finally block is useful for cleanup tasks that must happen no matter what.

If both catch and finally have return statements, the finally return overrides the catch return.

Summary

The finally block always runs after try and catch, even if there is an error or a return.

Use finally to clean up resources or run important code that must not be skipped.