Custom Exceptions in C++: Creating Application-Specific Error Types
What is Custom Exceptions in C++: Creating Application-Specific Error Types? Custom exceptions are created by deriving from std::exception, std::runtime_error, or std::logic_error and overriding the virtual const char* what() const noexc...
How do you create custom exception classes in C++ by inheriting from std::exception or std::runtime_error?
Explanation & In-Depth Details
Inheriting from `std::runtime_error` is the most common approach because it handles string storage internally:
```text
CUSTOM EXCEPTION HIERARCHY:
┌────────────────────────┐
│ std::runtime_error │
└───────────┬────────────┘
│
┌───────────┴────────────┐
│ NetworkTimeoutError │ ──► provides errorCode + what()
└────────────────────────┘
```
2. Overriding `what()`:
`const char* what() const noexcept override` must be marked `noexcept` to match the standard signature.
Code Example
#include <iostream>
#include <string>
#include <stdexcept>
// Custom Exception inheriting from std::runtime_error
class InsufficientFundsException : public std::runtime_error {
private:
double currentBalance;
double requestedAmount;
public:
InsufficientFundsException(double balance, double requested)
: std::runtime_error("Insufficient funds for requested transaction."),
currentBalance(balance),
requestedAmount(requested) {}
double getBalance() const noexcept { return currentBalance; }
double getRequested() const noexcept { return requestedAmount; }
};
void withdraw(double& balance, double amount) {
if (amount > balance) {
throw InsufficientFundsException(balance, amount);
}
balance -= amount;
std::cout << "Withdrew $" << amount << ". New balance: $" << balance << "\n";
}
int main() {
double accountBalance = 250.00;
try {
withdraw(accountBalance, 100.00);
withdraw(accountBalance, 500.00); // Exceeds balance
}
catch (const InsufficientFundsException& ex) {
std::cerr << "[Exception Caught]: " << ex.what() << "\n"
<< " Balance: $" << ex.getBalance() << "\n"
<< " Attempted: $" << ex.getRequested() << "\n";
}
return 0;
}Interview Question & Tips
A: `std::runtime_error` already encapsulates an `std::string` message and implements `.what()`, reducing boilerplate code in your custom exception.
Q: Why must `what()` be declared `noexcept`?
A: In `std::exception`, `what()` is defined as `virtual const char* what() const noexcept;`. In C++, an overriding method cannot have a looser exception specification than the base method.
Best Practices
• Include helpful contextual telemetry (error codes, usernames, transaction IDs) in custom exception classes.
• Catch custom exceptions before generic base exceptions in try-catch chains to ensure specific handling.
This study reference for Custom Exceptions in C++: Creating Application-Specific Error Types is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: