📌 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.
std::exception and override the what() virtual member function with the noexcept specifier.
#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;
}
std::runtime_error or std::logic_error allows you to pass error messages directly to the base constructor.
#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;
}
ServerException subclasses) while specific handlers catch individual anomalies.
#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;
}
#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;
}
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`. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘