Quick Answer
Manage errors with try-catch blocks.
Understanding the Issue
C++ exceptions provide a way to handle runtime errors without cluttering normal code flow with error checks.
The Problem
This code demonstrates the issue:
Cpp
Error
// Need to handle potential errors safely
The Solution
Here's the corrected code:
Cpp
Fixed
#include <iostream>
#include <stdexcept>
double divide(double a, double b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
return a / b;
}
int main() {
try {
double result = divide(10, 0);
std::cout << "Result: " << result << std::endl;
}
catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Unknown error occurred" << std::endl;
}
return 0;
}
Key Takeaways
Use exceptions for error handling in C++ rather than error codes.