How to Use finally in PHP: Syntax and Examples
In PHP, the
finally block is used after try and catch blocks to run code that must execute regardless of whether an exception was thrown or caught. It is useful for cleanup tasks like closing files or releasing resources.Syntax
The finally block follows try and optional catch blocks. It always runs after them, whether an exception occurs or not.
- try: Code that might throw an exception.
- catch: Code to handle exceptions.
- finally: Code that runs no matter what.
php
<?php try { // Code that may throw an exception } catch (Exception $e) { // Handle exception } finally { // Code that always runs } ?>
Example
This example shows how finally runs whether or not an exception is thrown. It prints messages to show the flow.
php
<?php function testFinally($throw) { try { echo "Inside try block\n"; if ($throw) { throw new Exception("An error occurred"); } echo "No exception thrown\n"; } catch (Exception $e) { echo "Caught exception: " . $e->getMessage() . "\n"; } finally { echo "Finally block always runs\n"; } } testFinally(false); echo "---\n"; testFinally(true); ?>
Output
Inside try block
No exception thrown
Finally block always runs
---
Inside try block
Caught exception: An error occurred
Finally block always runs
Common Pitfalls
One common mistake is to think finally only runs if an exception occurs. It runs always, even if no exception is thrown. Another pitfall is to put return statements inside try or catch and expect finally to not run; finally still executes before the function returns.
php
<?php function testReturn() { try { echo "Try block\n"; return "Returning from try"; } catch (Exception $e) { echo "Catch block\n"; } finally { echo "Finally block runs even with return\n"; } } echo testReturn(); ?>
Output
Try block
Finally block runs even with return
Returning from try
Quick Reference
- try: Wrap code that might fail.
- catch: Handle errors.
- finally: Always run cleanup code.
- finally runs even if
returnis used intryorcatch.
Key Takeaways
The finally block always runs after try and catch, no matter what.
Use finally for cleanup tasks like closing files or releasing resources.
Finally runs even if try or catch blocks have return statements.
You can use finally without catch, but try and finally must be together.
Finally helps keep your code safe and clean by guaranteeing execution.