C++ CUSTOM EXCEPTIONS ARCHITECTURE: INHERITING FROM STD::EXCEPTION & ERROR HIERARCHIES

Master building professional domain-specific error hierarchies in C++: inheriting from std::exception and std::runtime_error, overriding the what() virtual method, designing nested exception subsystems, and catching errors polymorphically.

📌 Why Create Custom Exceptions in C++?

While standard exceptions like std::out_of_range or std::runtime_error cover basic runtime failures, enterprise applications require precise domain-specific error modeling. Throwing primitive types (like strings or integers) or generic standard exceptions lacks context. By creating custom exception classes that inherit from std::exception (or standard subclasses like std::runtime_error), you establish clear, polymorphic error hierarchies that allow callers to catch specific subsystem failures (e.g., DatabaseException, NetworkException, AuthException) separately from general system faults.

1. Basic Custom Exception Inheriting from `std::exception`
To integrate smoothly with standard C++ exception handling, a custom exception class should publicly inherit from std::exception and override the what() virtual member function with the noexcept specifier.
C++ (basic_custom_exception.cpp)
#include 
#include 
#include 

// Custom Exception inheriting directly from std::exception
class InvalidAgeException : public std::exception {
private:
    std::string message;

public:
    InvalidAgeException(int age) {
        message = "InvalidAgeException: Age " + std::to_string(age) + " is outside allowable range [0-120].";
    }

    // Override what() method (marked noexcept for safety during unwinding)
    const char* what() const noexcept override {
        return message.c_str();
    }
};

void setVisitorAge(int age) {
    if (age < 0 || age > 120) {
        throw InvalidAgeException(age);
    }
    std::cout << "Age " << age << " registered successfully.\n";
}

int main() {
    try {
        setVisitorAge(150);
    } 
    catch (const InvalidAgeException& e) {
        std::cerr << "Caught Custom Exception: " << e.what() << "\n";
    }
    return 0;
}
Output: Caught Custom Exception: InvalidAgeException: Age 150 is outside allowable range [0-120].
2. Inheriting from `std::runtime_error` (Cleaner Syntax)
Writing boilerplate string formatting for every custom exception can be tedious. Inheriting from std::runtime_error or std::logic_error allows you to pass error messages directly to the base constructor.
C++ (runtime_error_inheritance.cpp)
#include 
#include 
#include 

// Inheriting from std::runtime_error automatically implements what() logic
class DatabaseConnectionException : public std::runtime_error {
public:
    DatabaseConnectionException(const std::string& dbName) 
        : std::runtime_error("Database Error: Failed to connect to cluster [" + dbName + "]") {}
};

void initializeDatabase(const std::string& name) {
    if (name.empty()) {
        throw DatabaseConnectionException("Unspecified_Cluster");
    }
    std::cout << "Connected to database: " << name << "\n";
}

int main() {
    try {
        initializeDatabase("");
    } 
    catch (const DatabaseConnectionException& e) {
        std::cerr << "[Critical Log] " << e.what() << "\n";
    }
    return 0;
}
Output: [Critical Log] Database Error: Failed to connect to cluster [Unspecified_Cluster]
3. Designing a Hierarchical Exception Subsystem
Enterprise software typically organizes exceptions into parent-child hierarchies. This allows a broad catch block to handle an entire subsystem error (e.g., catching all ServerException subclasses) while specific handlers catch individual anomalies.
C++ (exception_hierarchy.cpp)
#include 
#include 
#include 

// Base Application Exception
class ApplicationException : public std::runtime_error {
public:
    ApplicationException(const std::string& msg) : std::runtime_error("[App Error] " + msg) {}
};

// Subsystem Exceptions inheriting from ApplicationException
class NetworkTimeoutException : public ApplicationException {
public:
    NetworkTimeoutException() : ApplicationException("Network operation timed out.") {}
};

class UnauthorizedAccessException : public ApplicationException {
public:
    UnauthorizedAccessException(const std::string& user) 
        : ApplicationException("Access denied for user: " + user) {}
};

void executeTransaction(int code) {
    if (code == 1) throw NetworkTimeoutException();
    if (code == 2) throw UnauthorizedAccessException("root_admin");
}

int main() {
    for (int testCode : {1, 2}) {
        try {
            executeTransaction(testCode);
        } 
        catch (const ApplicationException& e) {
            // Polymorphically catches any subclass inheriting from ApplicationException
            std::cerr << "Caught Subsystem Fault: " << e.what() << "\n";
        }
    }
    return 0;
}
Output: Caught Subsystem Fault: [App Error] Network operation timed out. Caught Subsystem Fault: [App Error] Access denied for user: root_admin
4. Real-Time Example: Financial Transaction Processor with Custom Errors
A production-grade real-time example: a banking transaction processor that throws specific custom exceptions for insufficient funds, negative deposits, and frozen accounts.
C++ (financial_processor.cpp)
#include 
#include 
#include 

// Custom Banking Exception Hierarchy
class BankingException : public std::runtime_error {
public:
    BankingException(const std::string& msg) : std::runtime_error("Banking Error: " + msg) {}
};

class InsufficientFundsException : public BankingException {
public:
    InsufficientFundsException(double requested, double available)
        : BankingException("Requested withdrawal $" + std::to_string(requested) + 
                           " exceeds available balance $" + std::to_string(available)) {}
};

class AccountFrozenException : public BankingException {
public:
    AccountFrozenException(const std::string& accNum)
        : BankingException("Account [" + accNum + "] is currently frozen due to security review.") {}
};

class BankAccount {
private:
    std::string accountNumber;
    double balance;
    bool isFrozen;

public:
    BankAccount(std::string accNum, double initialBal, bool frozen) 
        : accountNumber(accNum), balance(initialBal), isFrozen(frozen) {}

    void withdraw(double amount) {
        if (isFrozen) {
            throw AccountFrozenException(accountNumber);
        }
        if (amount > balance) {
            throw InsufficientFundsException(amount, balance);
        }
        balance -= amount;
        std::cout << "Withdrawal successful! New balance: $" << balance << "\n";
    }
};

int main() {
    std::cout << "============================================\n";
    std::cout << "💳 FINANCIAL TRANSACTION PROCESSOR DEMO\n";
    std::cout << "============================================\n";

    BankAccount acc("ACC-882190", 500.0, false);

    try {
        acc.withdraw(1200.0); // Triggers InsufficientFundsException
    } 
    catch (const BankingException& e) {
        std::cerr << "[Transaction Rejected] " << e.what() << "\n";
    }

    std::cout << "============================================\n";
    return 0;
}
Output: ============================================ 💳 FINANCIAL TRANSACTION PROCESSOR DEMO ============================================ [Transaction Rejected] Banking Error: Requested withdrawal $1200.000000 exceeds available balance $500.000000 ============================================
5. Summary Reference Matrix: Custom Exceptions Best Practices
A comprehensive reference summary mapping out custom exception design patterns, inheritance rules, and polymorphism guidelines.
C++ Custom Exceptions Reference Matrix
C++ CUSTOM EXCEPTIONS ARCHITECTURE MATRIX:
┌──────────────────────────────┬─────────────────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Design Pattern / Rule        │ Implementation Syntax                   │ Engineering Purpose & Behavior                          │
├──────────────────────────────┼─────────────────────────────────────────┼─────────────────────────────────────────────────────────┤
│ Direct Inheritance           │ `class MyEx : public std::exception`    │ Requires manual `what()` override and string storage.   │
│ Standard Runtime Inheritance │ `class MyEx : public std::runtime_error`│ Simplifies string messaging via base constructor.       │
│ `noexcept` Specifier         │ `const char* what() const noexcept`     │ Guarantees `what()` never throws exceptions itself.     │
│ Polymorphic Catching         │ `catch (const BaseEx& e)`               │ Intercepts any current or future derived error types.   │
│ Error Hierarchies            │ Domain-Specific Subclassing             │ Models real-world subsystem failure categories cleanly. │
├──────────────────────────────┴─────────────────────────────────────────┴─────────────────────────────────────────────────────────┤
│ ENGINEERING BEST PRACTICES:                                                                                                      │
│ 1. Always catch custom exceptions by reference (`const CustomException& e`) to preserve polymorphism and avoid slicing.          │
│ 2. Derive domain-specific exceptions from `std::runtime_error` or `std::logic_error` rather than raw `std::exception`.           │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Design modular custom exception hierarchies for your enterprise libraries, ensuring error messages are descriptive, structured, and caught polymorphically at system boundaries.