C++
Error handling
Safely catch invalid inputs with try/catch.
Error handling
In division, dividing by zero is a major problem: a / 0 is undefined and may crash the program. So before dividing, we must check whether b is zero.
In C++, the if statement checks a condition. Writing if (b == 0) runs the following block only when b is zero. This way you catch the error and return a safe value.
In this project we will return 0 when dividing by zero. In a real app you could print an error message or throw an exception; for now we keep it simple.
Conditions with if
The if statement runs a block when a condition is true. The syntax is if (condition) { ... }. If the condition is true the block runs; if false it is skipped.
For a zero check: if (b == 0) return 0;. Here == is an equality comparison (do not confuse it with assignment =). If b is zero, the method returns 0 and no division happens.
Because return exits the method immediately, the return a / b; line after the check runs only when b is not zero. This structure is called an early return.
Exercise Add a zero check
Change the divide method body: first add if (b == 0) return 0; for the zero check, then return a / b; for normal division. The main already calls calc.divide(20, 4) and calc.divide(20, 0); the output must be 5 and 0.
Show example solution
#include <iostream>
class Calculator {
public:
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) {
if (b == 0) return 0;
return a / b;
}
};
int main() {
Calculator calc;
// Add a zero check to divide
std::cout << calc.divide(20, 4) << std::endl;
std::cout << calc.divide(20, 0) << std::endl;
return 0;
}
Test yourself
-
What should be done when the divisor is zero?
- The program crashes
- The result is 0
- Check first and return 0
- A compile error is raised
Show answer
Check first and return 0 — First check with if (b == 0) and return a safe value.
-
Zero check
if (____) return 0;
Show answer
if (b == 0) return 0;
-
Match error handling concepts
- if (b == 0)
- Zero check
- return 0;
- Safe value
- ==
- Equality comparison
- early return
- Early exit
Next lesson: Putting it together