Bird
Raised Fist0
PHPprogramming~5 mins

Finally block behavior in PHP

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the finally block in PHP exception handling?
easy
A. To stop the script execution immediately
B. To catch exceptions thrown in the try block
C. To execute code regardless of whether an exception was thrown or caught
D. To define the code that might throw an exception

Solution

  1. Step 1: Understand the roles of try, catch, and finally

    The try block contains code that may throw exceptions, catch handles those exceptions, and finally runs code after both regardless of exceptions.
  2. Step 2: Identify the unique role of finally

    The finally block always executes, even if an exception is not thrown or is caught, making it ideal for cleanup.
  3. Final Answer:

    To execute code regardless of whether an exception was thrown or caught -> Option C
  4. Quick Check:

    finally always runs = D [OK]
Hint: finally always runs after try/catch blocks [OK]
Common Mistakes:
  • Confusing finally with catch block
  • Thinking finally only runs on exceptions
  • Assuming finally stops script execution
2. Which of the following is the correct syntax for using a finally block in PHP?
easy
A. try { /* code */ } finally (Exception $e) { /* cleanup */ }
B. try { /* code */ } catch (Exception $e) { /* handle */ } finally() { /* cleanup */ }
C. try { /* code */ } catch { /* handle */ } finally { /* cleanup */ }
D. try { /* code */ } catch (Exception $e) { /* handle */ } finally { /* cleanup */ }

Solution

  1. Step 1: Recall PHP try-catch-finally syntax

    The correct syntax requires try, then catch with exception parameter, then finally without parameters or parentheses.
  2. Step 2: Check each option for syntax errors

    try { /* code */ } catch (Exception $e) { /* handle */ } finally { /* cleanup */ } matches correct syntax. try { /* code */ } finally (Exception $e) { /* cleanup */ } wrongly uses parameters in finally. try { /* code */ } catch { /* handle */ } finally { /* cleanup */ } misses exception variable in catch. try { /* code */ } catch (Exception $e) { /* handle */ } finally() { /* cleanup */ } wrongly uses parentheses after finally.
  3. Final Answer:

    try { /* code */ } catch (Exception $e) { /* handle */ } finally { /* cleanup */ } -> Option D
  4. Quick Check:

    Correct try-catch-finally syntax = B [OK]
Hint: finally block has no parameters or parentheses [OK]
Common Mistakes:
  • Adding parameters to finally block
  • Omitting exception variable in catch
  • Using parentheses after finally keyword
3. What will be the output of the following PHP code?
function test() {
  try {
    echo "Try block\n";
    return 1;
  } catch (Exception $e) {
    echo "Catch block\n";
  } finally {
    echo "Finally block\n";
  }
}
echo test();
medium
A. Try block 1 Finally block
B. Try block Finally block 1
C. Finally block Try block 1
D. Try block Catch block Finally block 1

Solution

  1. Step 1: Trace the try block execution

    The try block prints "Try block" and then returns 1 immediately.
  2. Step 2: Understand finally block runs after return

    Even though return is called, the finally block executes next, printing "Finally block" before the function returns.
  3. Final Answer:

    Try block Finally block 1 -> Option B
  4. Quick Check:

    finally runs after return = A [OK]
Hint: finally runs even after return statement [OK]
Common Mistakes:
  • Assuming finally does not run after return
  • Expecting catch block to run without exception
  • Misordering output lines
4. Identify the error in the following PHP code snippet:
try {
  throw new Exception("Error!");
} catch (Exception $e) {
  echo "Caught: " . $e->getMessage();
} finally {
  echo "Cleanup";
}
medium
A. There is no error; the code runs correctly
B. The catch block is missing the exception variable
C. The finally block cannot be used without a return statement
D. The throw statement must be inside the finally block

Solution

  1. Step 1: Check syntax and logic of try-catch-finally

    The try block throws an exception, the catch block catches it and prints the message, and finally prints "Cleanup".
  2. Step 2: Verify if any syntax or runtime errors exist

    All blocks are correctly formed, exception variable is present, and finally block is valid without return.
  3. Final Answer:

    There is no error; the code runs correctly -> Option A
  4. Quick Check:

    Valid try-catch-finally syntax = A [OK]
Hint: finally block is optional and valid without return [OK]
Common Mistakes:
  • Thinking finally requires return statement
  • Missing exception variable in catch
  • Misplacing throw statement
5. Consider this PHP function:
function process() {
  try {
    echo "Start\n";
    throw new Exception("Oops");
    return 10;
  } catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "\n";
    return 20;
  } finally {
    echo "Finally runs\n";
    return 30;
  }
}
echo process();

What will be the output when calling process()?
hard
A. Start Caught: Oops Finally runs 30
B. Start Finally runs 30
C. Start Caught: Oops Finally runs 20
D. Start Caught: Oops 20

Solution

  1. Step 1: Trace the try block and exception

    The try block prints "Start", then throws an exception, so the return 10 is skipped.
  2. Step 2: Catch block runs and returns 20

    The catch block prints "Caught: Oops" and returns 20, but before returning, finally block executes.
  3. Step 3: Finally block runs and overrides return

    The finally block prints "Finally runs" and returns 30, which overrides previous returns.
  4. Final Answer:

    Start Caught: Oops Finally runs 30 -> Option A
  5. Quick Check:

    finally return overrides others = C [OK]
Hint: Return in finally overrides try/catch returns [OK]
Common Mistakes:
  • Ignoring that finally return overrides catch return
  • Assuming catch return is final
  • Missing output order of prints
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard