0
0
PHPprogramming~30 mins

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

Choose your learning style9 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
Need a 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
Need a 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
Need a 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
Need a hint?

Change $errorOccurred to false to avoid the exception.