C++ Programming: Objects, RAII and the STL · The Standard Library

Exceptions: throw, try, catch

Throw an exception for bad input and catch it, skipping the rest of the try block.

exceptions.cpp

#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;
}

Step by step

  1. result is created on the stack with the value -1.
  2. divide(10, 4) works: 2.5.
  3. C++ checks b == 0 to decide which way the code goes.
  4. The method returns a / b.
  5. divide() has finished, so its variables are gone. The value it returned, 2.5, is stored in result.
  6. divide(1, 0)…
  7. C++ checks b == 0 to decide which way the code goes.
  8. throw creates the exception and leaves divide at once.
  9. The value it returned, an invalid_argument object, is stored in e.
  10. The matching catch runs. "not reached" was skipped.
  11. e goes out of scope and disappears.
  12. It prints 2.5.
  13. The method returns 0.
  14. caught: divide by zero, then 2.5.