Finally Block in PHP

The finally block in PHP is a block of code, which follows a try or catch block. It is always executed whether the catch block has handled the exception thrown by try block or not.

The finally block is mainly used for cleanup operations such as

  • Closing database connections.
  • Closing file handles.
  • Releasing system resources.
  • Logging application activity.
  • Ensuring that cleanup code always runs.

Syntax of Finally Block in PHP


The basic syntax for finally block with try and catch blocks is as follows:

Try-Finally Syntax

try {
    // Code that may throw an exception
} finally {
     // Code that always executes
}

In the above syntax:

  • The finally is a keyword, followed by a block of code.
  • The try block contains code that may generate an exception.
  • The finally block always execute, whether an exception occurs or not inside the try block.
  • No catch block is used in the above syntax.
  • If an exception occurs, PHP executes the finally block before propagating the exception and terminating the script (if unhandled). In simple words, the the finally block executes first and then the exception is passed to the calling code.
  • The finally block is used only with try block. It cannot exist without try block.

[blocksy-content-block id=”12371″]

Try-Catch-Finally Syntax

try {
   // Code that may throw an exception.
} catch (Exception $e) {
     // Code to handle the exception.
} finally {
     // Code that always executes.
}

In the above syntax:

  • The try block contains the code that may throw an exception.
  • The catch block catches and handles the exception thrown by the try block. It prevents script termination immediately.
  • The finally block executes after the execution of try and catch blocks.
  • The finally block always executes even if:
    • No exception occurs inside the try block.
    • A catch block catches an exception or not.
    • A return statement is used inside the try or catch block.
  • There may be multiple catch blocks before finally, but only one finally block is allowed per try block.

Examples of Finally Block in PHP


Let us take some important example programs based on the combination of try-catch-finally blocks in PHP.

Example 1: Try-Finally Block without Catch

<?php
try {
    echo "No exception occurs inside the try block.";
} finally {
     echo "Finally block always gets executed.";
}
?>

Output:

No exception occurs inside the try block.
Finally block always gets executed.

In this example:

  • No exception occurs inside the try block. Therefore, the code inside try block executes normally from start to end.
  • After the complete execution of the try block, control transfers to the finally block.
  • Since no exception occurs, no catch block executes.
  • The finally block runs immediately after try block.
  • The finally block always executes, regardless of exceptions occurs or not.

[blocksy-content-block id=”12121″]

Example 2: Try-Catch-Finally Block with No Exception

<?php
try {
   echo "No exception occurs inside the try block. \n";
} catch (Exception $e){
     echo "Catch block does not execute because of no exception occurring in try block";
}
finally {
    echo "Finally block always gets executed.";
}
?>

Output:

No exception occurs inside the try block. 
Finally block always gets executed.

In this example:

  • No exception occurs inside the try block. The code inside try executes completely without errors.
  • Since no exception is thrown by the try block, so the catch block will not execute and PHP skips the catch block.
  • The control of execution immediately transfers to the finally block after the complete execution of try block.
  • The finally block now executes because the finally block always runs, regardless of whether an exception occurs.

Example 3: Try-Catch-Finally Block with Exception

<?php
try {
    $num = 10 / 0; // This will cause an exception.
    echo "Result: $num";
} catch (DivisionByZeroError $e) {
     echo "Exception caught: Division by zero. \n";
} finally {
     echo "Finally block executed.";
}
?>

Output:

Exception caught: Division by zero. 
Finally block executed.

In this example:

  • The try block contains code that may throw an exception.
  • PHP automatically throws a DivisionByZeroError exception when a number is divided by zero. This is a built-in error exception in modern PHP.
  • PHP automatically throws exceptions for certain runtime errors, such as:
    • Division by zero → DivisionByZeroError
    • Type errors → TypeError
    • Undefined argument types (in strict typing)
    • Invalid operations
  • So, we don’t need to throw an exception manually here. However, we can also manually throw exceptions when any logic fails.
  • When the exception occurs inside the try block, PHP immediately stops executing the remaining code in the try block.
  • The control immediatly transfers to the catch block, where it catch the exception thrown by the try block and handles the error gracefully.
  • After the complete execution of catch block, the control always transfers to the finally block.

[blocksy-content-block id=”12153″]

Example 4: Finally Block with Multiple Catch Blocks

<?php
try {
    $num = 10 / 0; // This will cause a DivisionByZeroError.
    echo "Result: $num";
} catch (DivisionByZeroError $e) {
      echo "Error: Division by zero occurred. \n";
} catch (TypeError $e) {
      echo "Error: Invalid data type. \n";
} catch (Exception $e) {
      echo "General exception occurred. \n";
} finally {
      echo "Finally block executed.";
}
?>

Output:

Error: Division by zero occurred. 
Finally block executed.

In this example:

  • The try block contains code that may generate a DivisionByZeroError exception. Dividing by zero in PHP triggers DivisionByZeroError.
  • The control immediately transfers to multiple catch blocks to handle exceptions.
  • PHP checks the catch blocks from top to bottom because PHP matches catch blocks sequentially in the order they appear.
  • The first catch (DivisionByZeroError $e) block catches and handles the exception thrown by the try block. This is the first matching and most specific catch block to handle DivisionByZeroError exception.
  • PHP skips the remaining catch blocks because the exception has already been handled by the first matching catch block.
  • The catch (Exception $e) block acts as a fallback handler for general exceptions.
  • After the execution of matched catch block, the control goes to the finally block.
  • The finally block executes after the try or catch block.
  • In multiple catch blocks, the order should be the most specific to general.

Example 5: Finally Block with Return Statement

<?php
function testFinallyReturn() {
   try {
      return "Returned from try block. \n";
   } catch (Exception $e) {
         return "Returned from catch block. \n";
   } finally {
         echo "Finally block executed.\n";
   }
}
echo testFinallyReturn();
?>

Output:

Finally block executed.
Returned from try block.

In this example:

  • We have defined a function named testFinallyReturn() that contains a try–catch–finally block.
  • When the function is called, the try block executes.
  • The try block contains the return statement, which is executed in the try block.
  • PHP does not exit the function immediately. It first ensures that the finally block is executed.
  • The finally block executes before the function actually returns.
  • After the finishing execution of finally block, the control returns the value from the try block.
  • The catch block is skipped because no exception occurs in the try block.
  • The finally block always executes, even when return statement is used inside the try or catch block.
  • A return statement in try or catch block does not prevent finally block from executing.

Conclusion

PHP provides a powerful mechanism to handle runtime errors and exceptions using try, catch, and finally blocks. Among these, the finally block plays a specific role in PHP that always guarantees the execution of certain code, regardless of whether an exception occurs.

If you are working with files, databases, APIs, or system resources, using the finally block is considered a best practice in modern PHP development. We hope that this tutorial has helped you understand the finally block in PHP and practiced all important examples based on it.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.