C++ · Module 15 · Lesson 21 min read

Custom Exception Classes

Deriving from the standard hierarchy ✅

arduino
class InsufficientFunds : public std::runtime_error {
public:
    InsufficientFunds(double needed, double available)
        : std::runtime_error("insufficient funds"), needed_(needed), available_(available) {}
    double shortfall() const { return needed_ - available_; }
private:
    double needed_, available_;
};
  • Inherit from std::runtime_error or std::logic_error (or std::exception)
  • Pass a message to the base constructor → what() works
  • Add extra data callers can use (amounts, file names, error codes, line numbers)

A hierarchy for your app

c
AppError : std::runtime_error
├── ValidationError
├── StorageError
│   └── FileCorrupted
└── NetworkError

Callers can catch broadly (AppError) or narrowly (NetworkError).

Building good messages

Include what failed and why, with values: "Expense amount -50 is invalid (must be > 0)".

Rules

  • Exception classes should be cheap to copy and their constructors shouldn't throw
  • Don't store references or pointers to local data in an exception
  • what() is noexcept and returns const char*

std::system_error and error codes

For OS-level errors, std::system_error carries a std::error_code (e.g. from std::filesystem).

Nested exceptions

std::throw_with_nested(MyError("loading config")) inside a catch wraps the original exception — useful to add context while keeping the root cause (std::rethrow_if_nested).

Exceptions across boundaries

Don't let exceptions escape: destructors, noexcept functions, C callbacks, thread functions (catch and transfer with std::exception_ptr), main (catch and report).

Example

C++
#include <iostream>
#include <stdexcept>
#include <string>

class AppError : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
};

class ValidationError : public AppError {
public:
    ValidationError(const std::string& field, const std::string& problem)
        : AppError(field + ": " + problem), field_(field) {}
    const std::string& field() const { return field_; }
private:
    std::string field_;
};

class InsufficientFunds : public AppError {
public:
    InsufficientFunds(double needed, double available)
        : AppError("insufficient funds: need " + std::to_string(static_cast<long>(needed)) +
                   ", have " + std::to_string(static_cast<long>(available))),
          needed_(needed), available_(available) {}
    double shortfall() const { return needed_ - available_; }
private:
    double needed_, available_;
};

class StorageError : public AppError {
public:
    using AppError::AppError;
};

void pay(double balance, double amount, const std::string& note) {
    if (amount <= 0) throw ValidationError("amount", "must be greater than zero");
    if (note.empty()) throw ValidationError("note", "cannot be empty");
    if (amount > balance) throw InsufficientFunds(amount, balance);
    std::cout << "paid " << amount << " for " << note << '\n';
}

void load_settings() {
    try {
        throw std::runtime_error("settings.json: unexpected end of file");
    } catch (...) {
        std::throw_with_nested(StorageError("could not load settings"));   // add context, keep the cause
    }
}

void print_nested(const std::exception& e, int depth = 0) {
    std::cout << std::string(depth * 2, ' ') << "- " << e.what() << '\n';
    try { std::rethrow_if_nested(e); } catch (const std::exception& inner) { print_nested(inner, depth + 1); }
}

int main() {
    struct Case { double amount; const char* note; };
    for (Case c : { Case{ 500, "groceries" }, Case{ -10, "refund" }, Case{ 300, "" }, Case{ 9000, "phone" } }) {
        try {
            pay(2500, c.amount, c.note);
        } catch (const ValidationError& e) {
            std::cout << "please fix field '" << e.field() << "' (" << e.what() << ")\n";
        } catch (const InsufficientFunds& e) {
            std::cout << e.what() << " -> short by " << e.shortfall() << '\n';
        }
    }

    try {
        load_settings();
    } catch (const AppError& e) {                 // catch the whole family
        std::cout << "app error chain:\n";
        print_nested(e);
    }
    return 0;
}

/* Output:
paid 500 for groceries
please fix field 'amount' (amount: must be greater than zero)
please fix field 'note' (note: cannot be empty)
insufficient funds: need 9000, have 2500 -> short by 6500
app error chain:
- could not load settings
  - settings.json: unexpected end of file
*/