📖 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
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
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
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
Hint
The program will stop and show an error message because the withdrawal is too large.
Practice
(1/5)
1. What does the throw statement do in PHP?
easy
A. It catches an exception to handle an error.
B. It creates and signals an exception to indicate an error.
C. It defines a new function for error handling.
D. It stops the script without any error message.
Solution
Step 1: Understand the purpose of throw
The throw statement is used to create and signal an exception when an error occurs.
Step 2: Differentiate from other error handling keywords
catch handles exceptions, but throw actually creates and signals them.
Final Answer:
It creates and signals an exception to indicate an error. -> Option B
2. Which of the following is the correct syntax to throw an exception with the message "Error occurred" in PHP?
easy
A. throw new Exception("Error occurred");
B. throw Exception("Error occurred");
C. throw Exception new("Error occurred");
D. throw new Exception(Error occurred);
Solution
Step 1: Recall the syntax for throwing exceptions
In PHP, you must use throw new Exception("message") to throw an exception with a message.
Step 2: Check each option for syntax correctness
Only throw new Exception("Error occurred"); matches the correct syntax exactly. The other options either omit the new keyword, have the wrong order of keywords, or lack quotes around the message.
Final Answer:
throw new Exception("Error occurred"); -> Option A
Quick Check:
Correct syntax = throw new Exception(message) [OK]
Hint: Use 'throw new Exception("message")' exactly [OK]
Common Mistakes:
Omitting the 'new' keyword
Not quoting the message string
Wrong order of keywords
3. What will be the output of the following PHP code?
try {
throw new Exception("Oops!");
echo "No error";
} catch (Exception $e) {
echo $e->getMessage();
}
medium
A. No error
B. Fatal error
C. Exception thrown but no output
D. Oops!
Solution
Step 1: Analyze the try block
The code throws an exception with message "Oops!" before the echo statement, so "No error" is never printed.
Step 2: Understand the catch block behavior
The catch block catches the exception and echoes the message from the exception, which is "Oops!".
Final Answer:
Oops! -> Option D
Quick Check:
Exception message printed = Oops! [OK]
Hint: Exception stops try block; catch prints message [OK]
C. Method message() does not exist; should use getMessage().
D. Catch block syntax is incorrect.
Solution
Step 1: Check the catch block method call
The Exception class has a method getMessage() to get the error message, not message().
Step 2: Verify other syntax elements
The semicolon after throw is present, Exception class is built-in, and catch syntax is correct.
Final Answer:
Method message() does not exist; should use getMessage(). -> Option C
Quick Check:
Use getMessage() to get exception text [OK]
Hint: Use getMessage() method to read exception message [OK]
Common Mistakes:
Calling non-existent message() method
Missing semicolons (not in this case)
Incorrect catch syntax
5. You want to throw an exception only if a variable $age is less than 18. Which code correctly does this and catches the exception to print its message "Too young"?
hard
A. try {
if ($age < 18) {
throw new Exception("Too young");
}
} catch (Exception $e) {
echo $e->getMessage();
}
B. try {
if ($age < 18) {
throw new Exception("Too young");
}
} catch (Exception $e) {
echo "Too young";
}
C. try {
if ($age < 18) {
throw Exception("Too young");
}
} catch (Exception $e) {
echo $e->getMessage();
}
D. if ($age < 18) {
throw new Exception("Too young");
} catch (Exception $e) {
echo $e->getMessage();
}
Solution
Step 1: Identify correct try-catch structure
The exception must be thrown inside a try block to be caught properly. try {
if ($age < 18) {
throw new Exception("Too young");
}
} catch (Exception $e) {
echo $e->getMessage();
} correctly wraps the throw inside try.
Step 2: Check exception throwing syntax and catch output
try {
if ($age < 18) {
throw new Exception("Too young");
}
} catch (Exception $e) {
echo $e->getMessage();
} uses correct syntax throw new Exception("Too young") and prints the exception message with echo $e->getMessage();.
Final Answer:
try { if ($age < 18) { throw new Exception("Too young"); } } catch (Exception $e) { echo $e->getMessage(); } -> Option A
Quick Check:
Throw inside try, catch prints message [OK]
Hint: Always throw exceptions inside try blocks to catch them [OK]
Common Mistakes:
Throwing outside try block
Missing 'new' keyword when throwing
Printing hardcoded message instead of exception message
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.