C++ Programming: Objects, RAII and the STL · The Standard Library
Throw an exception for bad input and catch it, skipping the rest of the try block.
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw invalid_argument("divide by zero");
}
return a / b;
}
int main() {
double result = -1;
try {
result = divide(10, 4);
result = divide(1, 0);
cout << "not reached" << endl;
} catch (const invalid_argument &e) {
cout << "caught: " << e.what() << endl;
}
cout << result << endl;
return 0;
}result is created on the stack with the value -1.b == 0 to decide which way the code goes.a / b.divide() has finished, so its variables are gone. The value it returned, 2.5, is stored in result.b == 0 to decide which way the code goes.e.e goes out of scope and disappears.2.5.0.