0
0
PHPprogramming~15 mins

Throwing exceptions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Throwing exceptions
📖 Scenario: Imagine you are creating a simple bank account system. You want to make sure that if someone tries to withdraw more money than they have, the program will stop and show an error message.
🎯 Goal: You will build a PHP program that throws an exception when a withdrawal amount is greater than the account balance.
📋 What You'll Learn
Create a variable to hold the account balance
Create a variable for the withdrawal amount
Use an if statement to check if withdrawal is greater than balance
Throw an exception with a clear message if withdrawal is too large
Print a success message if withdrawal is allowed
💡 Why This Matters
🌍 Real World
Throwing exceptions is useful in real programs to stop execution when something goes wrong, like invalid input or errors.
💼 Career
Understanding exceptions is important for writing reliable and safe code in many programming jobs.
Progress0 / 4 steps
1
Set up account balance and withdrawal amount
Create a variable called $balance and set it to 1000. Create another variable called $withdrawal and set it to 1200.
PHP
Need a hint?

Use simple assignment to create the variables with the exact names and values.

2
Prepare to check withdrawal amount
Create a variable called $canWithdraw and set it to true. This will help us decide if withdrawal is allowed.
PHP
Need a hint?

This variable will be used to track if withdrawal is possible.

3
Throw exception if withdrawal is too large
Use an if statement to check if $withdrawal is greater than $balance. Inside the if, throw a new Exception with the message 'Withdrawal amount exceeds balance.'.
PHP
Need a hint?

Use throw new Exception('message'); inside the if block.

4
Print success message if no exception
Add a print statement that outputs 'Withdrawal successful.' after the if block.
PHP
Need a hint?

The program will stop and show an error message because the withdrawal is too large.