Bird
Raised Fist0
PHPprogramming~30 mins

Finally block behavior in PHP - Mini Project: Build & Apply

Choose your learning style10 modes available
Finally Block Behavior
📖 Scenario: Imagine you are writing a PHP script that processes a payment. You want to make sure that some cleanup code always runs, no matter if the payment succeeds or fails.
🎯 Goal: Build a PHP script that uses a try, catch, and finally block to handle an error and always run cleanup code.
📋 What You'll Learn
Create a variable $paymentStatus with the value 'pending'.
Create a variable $errorOccurred with the value true.
Use a try block that throws an Exception with the message 'Payment failed' if $errorOccurred is true.
Use a catch block to catch the Exception and set $paymentStatus to 'failed'.
Use a finally block to set $cleanupDone to true.
Print the values of $paymentStatus and $cleanupDone.
💡 Why This Matters
🌍 Real World
In real payment systems, you must always clean up resources like closing database connections or logging, even if an error happens.
💼 Career
Understanding exception handling and finally blocks is important for writing reliable PHP code in web development and backend services.
Progress0 / 4 steps
1
Create initial variables
Create a variable called $paymentStatus and set it to 'pending'. Also create a variable called $errorOccurred and set it to true.
PHP
Hint

Use = to assign values to variables. Strings need quotes.

2
Add try, catch, and finally blocks
Add a try block that throws an Exception with the message 'Payment failed' if $errorOccurred is true. Add a catch block to catch the Exception and set $paymentStatus to 'failed'. Add a finally block that sets $cleanupDone to true.
PHP
Hint

Use throw new Exception('message') inside try. Catch with catch (Exception $e). Use finally for cleanup.

3
Print the results
Print the values of $paymentStatus and $cleanupDone using echo. Separate them with a space.
PHP
Hint

Use echo to print. Use . to join strings. Convert boolean to string with a ternary.

4
Test with no error
Change the value of $errorOccurred to false and run the same code again. Print the values of $paymentStatus and $cleanupDone separated by a space.
PHP
Hint

Change $errorOccurred to false to avoid the exception.

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