Lesson 20 of 25

Exception Handling

Try-Catch and Custom Exceptions

C++ uses try-catch blocks for exception handling. You can throw any type, but standard and custom exception classes are preferred.

Example
#include <stdexcept>

// Throwing and catching
try {
    int age = -5;
    if (age < 0) {
        throw invalid_argument("Age cannot be negative");
    }
} catch (const invalid_argument& e) {
    cerr << "Error: " << e.what() << endl;
} catch (const exception& e) {
    cerr << "General error: " << e.what() << endl;
} catch (...) {
    cerr << "Unknown error" << endl;
}

// Custom exception class
class InsufficientFunds : public runtime_error {
public:
    InsufficientFunds(double needed)
        : runtime_error("Need $" + to_string(needed) + " more") {}
};

void withdraw(double amount, double balance) {
    if (amount > balance) {
        throw InsufficientFunds(amount - balance);
    }
}