Handling error cases
Add guards for division by zero and invalid operators.
Error cases
The calculator may not always receive correct input. There are two important error cases:
- Division by zero: if the divisor is 0, the result is undefined.
- Invalid operator: if the user enters a value other than
+,-,*,/, the operation cannot run.
We use an else branch to catch these cases. If no if/elseif condition matches, the else block runs and shows an error message to the user.
Catching with the else branch
The else branch is added at the end of an if/elseif chain and runs when no condition matches. This is the cleanest way to catch unknown operators.
} else {
$result = "Error: invalid operation";
}So if the user enters an operator like %, the program doesn't crash; instead it shows a clear error message. Error messages tell the user what went wrong.
Exercise Add an else branch for invalid operators
Add an else branch to catch invalid operators. In the else block, assign the message "Error: invalid operation" to $result. This way unknown operators show an error message.
Show example solution
Add an else branch at the end of the if/elseif chain.
Example solution:
<?php
// The first number entered by the user
$first = 25;
// The chosen operator and second number
$operator = "+";
$second = 4;
$result = 0;
if ($operator === "+") {
$result = $first + $second;
} elseif ($operator === "-") {
$result = $first - $second;
} elseif ($operator === "*") {
$result = $first * $second;
} elseif ($operator === "/") {
$result = $first / $second;
} else {
$result = "Error: invalid operation";
}
echo "Result: " . $result;
Test yourself
-
What should happen with an invalid operator?
- Set the result to 0
- Skip the operation
- Stop the program
- Show an error message
Show answer
Show an error message — The else branch shows an error for an invalid operator.
-
Assign an error message in the else branch
<?php if ($operator === "+") { $result = $first + $second; } else { $result = ____; } echo $result; ?>Show answer
<?php if ($operator === "+") { $result = $first + $second; } else { $result = "Error: invalid operation"; } echo $result; ?> -
Match each error to its cause
- Division by zero
- Divisor cannot be 0
- Invalid operation
- Operator is unknown
- Empty value
- Variable is empty