Topic 73 of 83
Custom Exceptions
Overview
For domain-specific errors (e.g., InsufficientFundsException for a bank), you can create your own exception classes by inheriting from std::exception.
Syntax
cpp
#include <exception>
class MyCustomError : public std::exception {
public:
// Overriding the what() method
const char* what() const noexcept override {
return "A highly specific custom error occurred!";
}
};
try {
throw MyCustomError();
} catch (const std::exception& e) {
cout << e.what();
}Common Pitfalls
- Forgetting to inherit from
std::exception. While you can throw any class, inheriting fromstd::exceptionensures your error is caught by genericcatch (const std::exception&)blocks.
Interview Questions
- The
noexceptkeyword in thewhat()method signature promises the compiler that thewhat()function itself will never throw an exception. This is required when overridingstd::exception::what().
Real-World Example
Custom exception for a banking application.
example
cpp
#include <iostream>
#include <exception>
using namespace std;
class InsufficientFunds : public exception {
public:
const char* what() const noexcept override {
return "Transaction Failed: Not enough money in account.";
}
};
void withdraw(int balance, int amount) {
if (amount > balance) {
throw InsufficientFunds();
}
cout << "Withdrawal successful.\n";
}
int main() {
try {
withdraw(100, 500);
} catch (const InsufficientFunds& e) {
cout << e.what() << endl;
}
return 0;
}