C++C++ · Lesson 7 of 9

Error Handling & Exceptions

C++ uses exceptions for error handling. They're controversial in some circles — many game engines and embedded systems disable them. Know them anyway.

C++
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

class InsufficientFundsException : public runtime_error {
    double amount, balance;
public:
    InsufficientFundsException(double amt, double bal)
        : runtime_error("Insufficient funds"),
          amount(amt), balance(bal) {}

    double getAmount() const { return amount; }
    double getBalance() const { return balance; }
};

double safeDivide(double a, double b) {
    if (b == 0) throw invalid_argument("Division by zero");
    return a / b;
}

void withdraw(double& balance, double amount) {
    if (amount > balance) {
        throw InsufficientFundsException(amount, balance);
    }
    balance -= amount;
}

int main() {
    // Basic try/catch
    try {
        double result = safeDivide(10, 0);
        cout << result << "
";
    } catch (const invalid_argument& e) {
        cout << "Error: " << e.what() << "
";
    }

    // Multiple catch blocks
    double balance = 100.0;
    try {
        withdraw(balance, 50);   // OK
        cout << "Balance: " << balance << "
";
        withdraw(balance, 200);  // throws
    } catch (const InsufficientFundsException& e) {
        cout << "Can't withdraw " << e.getAmount()
             << ", balance is " << e.getBalance() << "
";
    } catch (const exception& e) {
        cout << "Generic error: " << e.what() << "
";
    } catch (...) {
        cout << "Unknown error
";  // catch anything
    }

    // Standard exception types:
    // std::runtime_error — general runtime failure
    // std::invalid_argument — bad function argument
    // std::out_of_range — value out of valid range
    // std::overflow_error — arithmetic overflow

    return 0;
}
⚠ Warning
Exceptions have overhead — they're not free even when none are thrown. For performance-critical code, consider returning error codes or using std::expected (C++23) or std::optional instead.