📖 Scenario: Imagine you are writing a simple PHP script that divides two numbers. Sometimes, the divisor might be zero, which causes an error. You want to handle this error gracefully so your program doesn't crash.
🎯 Goal: You will create a PHP script that uses try and catch blocks to handle division by zero errors and print appropriate messages.
📋 What You'll Learn
Create two variables for the dividend and divisor with exact values
Create a variable to hold the result initialized to null
Use a try-catch block to perform division and catch division by zero exceptions
Print the result or an error message depending on the execution flow
💡 Why This Matters
🌍 Real World
Handling errors like division by zero is important in real applications to avoid crashes and provide user-friendly messages.
💼 Career
Understanding try-catch blocks is essential for writing robust PHP code in web development and backend programming.
Progress0 / 4 steps
1
DATA SETUP: Create dividend and divisor variables
Create two variables called $dividend and $divisor with values 10 and 0 respectively.
PHP
Hint
Use $dividend = 10; and $divisor = 0; to create the variables.
2
CONFIGURATION: Create a result variable
Create a variable called $result and set it to null to hold the division result.
PHP
Hint
Initialize $result with null before the try-catch block.
3
CORE LOGIC: Use try-catch to handle division
Write a try block where you divide $dividend by $divisor and assign it to $result. Then write a catch block to catch DivisionByZeroError and set $result to the string 'Error: Division by zero.'.
PHP
Hint
Use try { $result = $dividend / $divisor; } and catch DivisionByZeroError to set the error message.
4
OUTPUT: Print the result
Write a print statement to display the value of $result.
PHP
Hint
Use print($result); to show the output.
Practice
(1/5)
1.
What is the main purpose of a try-catch block in PHP?
easy
A. To handle errors without stopping the program
B. To speed up the execution of the program
C. To create new variables automatically
D. To print output to the screen
Solution
Step 1: Understand the role of try-catch
The try block contains code that might cause an error, and the catch block handles that error.
Step 2: Identify the purpose
This structure prevents the program from stopping abruptly by managing errors gracefully.
Final Answer:
To handle errors without stopping the program -> Option A
Quick Check:
Try-catch = error handling [OK]
Hint: Try-catch is for error handling, not speed or output [OK]
Common Mistakes:
Thinking try-catch speeds up code
Confusing try-catch with output commands
Believing try-catch creates variables
2.
Which of the following is the correct syntax to start a try-catch block in PHP?