PHP Exception Handling: Divide with zero denominator check
3. Division with Exception Handling
Write a PHP program that implements a PHP function that divides two numbers but throws an exception if the denominator is zero.
Sample Solution:
PHP Code :
<?php
function divideNumbers($numerator, $denominator) {
if ($denominator === 0) {
throw new Exception("Division by zero is not allowed.");
}
return $numerator / $denominator;
}
try {
$result = divideNumbers(200, 0);
echo "Result: " . $result;
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
?>
Sample Output:
An error occurred: Division by zero is not allowed.
Explanation:
In the above exercise,
- The divideNumbers() function takes two parameters, $numerator and $denominator. Inside the function, we check if the $denominator is zero. If it is, we throw a new instance of the Exception class with the message "Division by zero is not allowed."
- The function returns the division result if the denominator is non-zero.
- In the main code, we call the divideNumbers() function with arguments 10 and 0, which triggers an exception. The exception is caught in the catch block, and we display the error message using $e-<getMessage().
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP function that divides two numbers and throws an exception if the denominator is zero, then catches it to display a user-friendly message.
- Write a PHP script to validate numeric inputs before division, throwing an exception for invalid types, and handling the exception gracefully.
- Write a PHP program that performs division within a try block and uses custom exception messages to indicate whether division was possible or not.
- Write a PHP script to implement division in a function that checks for a zero denominator and demonstrates exception chaining in the catch block.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Creating and throwing custom exceptions.
Next: Try-Catch blocks for error messages.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.