PHP Exception Handling with finally

In PHP, the finally block is used with try-catch statements to ensure that certain code always executes, regardless of whether an exception occurs or not. This block appears after the catch block or can be used instead of a catch block.

Syntax

The finally block can be used in two ways −

try {
    // Code that may throw an exception
} catch (Exception $e) {
    // Handle exception
} finally {
    // Always executed
}

// OR without catch block
try {
    // Code that may throw an exception
} finally {
    // Always executed
}

Using try-catch-finally

When both catch and finally blocks are present, the finally block executes after the catch block handles any exception ?

<?php
function divide($x, $y) {
    if (!$y) {
        throw new Exception('Division by zero.');
    }
    return $x/$y;
}

try {
    echo divide(10, 0) . "<br>";
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "<br>";
} finally {
    echo "Finally block always executed<br>";
}

echo "Program continues<br>";
?>
Caught exception: Division by zero.
Finally block always executed
Program continues

Example Without Exception

When no exception occurs, only the finally block executes after the try block ?

<?php
function divide($x, $y) {
    if (!$y) {
        throw new Exception('Division by zero.');
    }
    return $x/$y;
}

try {
    echo divide(10, 5) . "<br>";
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "<br>";
} finally {
    echo "Finally block always executed<br>";
}

echo "Program continues<br>";
?>
2
Finally block always executed
Program continues

Using try-finally Without catch

You can use finally without a catch block. This is useful for cleanup operations that must run regardless of exceptions ?

<?php
function divide($x, $y) {
    try {
        if (!$y) {
            throw new Exception('Division by zero.');
        }
        return $x/$y;
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "<br>";
        return null;
    }
}

try {
    $result = divide(10, 0);
    if ($result !== null) {
        echo "Result: $result<br>";
    }
} finally {
    echo "Cleanup operations completed<br>";
}

echo "Program continues<br>";
?>
Caught exception: Division by zero.
Cleanup operations completed
Program continues

Key Points

Scenario Execution Order
Exception occurs try ? catch ? finally
No exception try ? finally
Only try-finally try ? finally (exception propagates)

Conclusion

The finally block ensures critical cleanup code always executes, making it ideal for resource management like closing files or database connections. It executes regardless of whether exceptions occur or are caught.

Updated on: 2026-03-15T09:10:23+05:30

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements