0
0
PHPprogramming~30 mins

Error vs Exception in PHP - Hands-On Comparison

Choose your learning style9 modes available
Understanding Error vs Exception in PHP
📖 Scenario: Imagine you are building a simple PHP script that processes user input and performs division. Sometimes, the input might cause errors or exceptions. Understanding how PHP handles errors and exceptions helps you write safer code.
🎯 Goal: You will create a PHP script that demonstrates the difference between an error and an exception by triggering each and handling the exception properly.
📋 What You'll Learn
Create a variable called numerator with the value 10
Create a variable called denominator with the value 0
Use a try block to attempt division and throw an Exception if denominator is zero
Use a catch block to catch the Exception and print the exception message
Trigger a PHP error by calling an undefined function undefinedFunction()
Print the result of the division if no exception occurs
💡 Why This Matters
🌍 Real World
Handling errors and exceptions properly is important in real-world PHP applications to avoid crashes and provide clear feedback to users.
💼 Career
Understanding error vs exception handling is a key skill for PHP developers to write robust and maintainable code.
Progress0 / 4 steps
1
Set up numerator and denominator variables
Create a variable called numerator and set it to 10. Create another variable called denominator and set it to 0.
PHP
Need a hint?

Use $numerator = 10; and $denominator = 0; to create the variables.

2
Add try block to check denominator and throw Exception
Add a try block. Inside it, check if $denominator is zero. If yes, throw a new Exception with the message 'Cannot divide by zero.'. Otherwise, calculate the division and store it in $result.
PHP
Need a hint?

Use throw new Exception('Cannot divide by zero.'); inside the if condition.

3
Add catch block and trigger a PHP error
Add a catch block to catch the Exception as $e and print the exception message using echo. After the try-catch, call an undefined function undefinedFunction() to trigger a PHP error.
PHP
Need a hint?

Use catch (Exception $e) and inside it echo "Exception caught: " . $e->getMessage();. Then call undefinedFunction(); outside the try-catch.

4
Print the division result if no exception
After the try-catch block, add a check to see if $result is set. If yes, print "Result: " followed by the value of $result.
PHP
Need a hint?

Use if (isset($result)) { echo "Result: " . $result; } to print the result only if it exists.