Bird
Raised Fist0
PHPprogramming~10 mins

Finally block behavior in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Finally block behavior
Try block starts
↓
Code runs in try
↓
Exception?
Yes→Catch block runs
↓
Catch code runs
↓
Try block ends
↓
Catch ends
↓
Finally block runs ALWAYS
↓
Code after try-catch-finally
The finally block runs no matter what happens in try or catch blocks, even if an exception occurs or not.
Execution Sample
PHP
<?php
try {
  echo "Try\n";
} catch (Exception $e) {
  echo "Catch\n";
} finally {
  echo "Finally\n";
}
This code prints messages from try, catch (if exception), and finally blocks.
Execution Table
StepBlockActionOutputNotes
1TryExecute try block codeTryNo exception thrown
2CatchSkippedNo exception to catch
3FinallyExecute finally blockFinallyRuns always
4AfterContinue after try-catch-finallyProgram continues normally
💡 Execution continues after finally block with rest of program
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Output"""Try\n""Try\n""Try\nFinally\n""Try\nFinally\n"
Key Moments - 3 Insights
Does the finally block run if an exception is thrown?
Yes, the finally block always runs whether or not an exception occurs, as shown in step 3 of the execution_table.
What happens if there is no catch block but a finally block exists?
The finally block still runs after the try block finishes, even if no catch block is present.
Can the finally block change the output even if an exception is thrown?
Yes, the finally block runs after try or catch and can add to output or perform cleanup.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed after the try block runs?
ACatch
BTry
CFinally
DNothing
💡 Hint
Check Step 1 in execution_table under Output column
At which step does the finally block run according to the execution_table?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for 'Finally' block execution in the Step column
If an exception was thrown in the try block, which block would run next before finally?
ACatch block
BFinally block immediately
CTry block again
DProgram ends
💡 Hint
Refer to concept_flow showing exception path to catch block
Concept Snapshot
try { ... } catch (Exception $e) { ... } finally { ... }
- finally block runs always, after try and catch
- runs even if exception occurs or not
- useful for cleanup code
- program continues after finally block
Full Transcript
In PHP, the finally block runs after the try and catch blocks no matter what. If the try block runs without error, the catch block is skipped, but finally still runs. If an exception occurs, the catch block runs, then finally runs. This ensures code in finally always executes, useful for cleanup. The execution table shows try prints 'Try', catch is skipped, then finally prints 'Finally'. The variable tracker shows output grows after try and finally. Key moments clarify that finally runs always, even without catch, and can affect output. The quiz checks understanding of when finally runs and what prints.

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