Exception Handling provides a structured mechanism to detect, transmit, and resolve unexpected runtime errors (such as network loss, missing files, or out-of-memory errors) without abruptly crashing the application.
#include <iostream>
#include <stdexcept>
#include <string>
// Custom domain exception deriving from std::runtime_error
class InsufficientFundsException : public std::runtime_error {
public:
explicit InsufficientFundsException(double deficit)
: std::runtime_error("Withdrawal rejected: Shortfall of $" + std::to_string(deficit)) {}
};
class BankAccount {
private:
double balance;
public:
BankAccount(double b) : balance(b) {}
void withdraw(double amount) {
if (amount > balance) {
throw InsufficientFundsException(amount - balance); // Throw custom exception
}
balance -= amount;
std::cout << "Withdrawal successful. Remaining: $" << balance << "\n";
}
};
int main() {
BankAccount account(500.0);
try {
account.withdraw(200.0);
account.withdraw(450.0); // Throws InsufficientFundsException!
} catch (const InsufficientFundsException& e) {
std::cerr << "[ACCOUNT ERROR]: " << e.what() << "\n";
} catch (const std::exception& e) {
std::cerr << "[STANDARD ERROR]: " << e.what() << "\n";
}
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
How RAII prevents leaks during stack unwinding.
Handling I/O stream exceptions.
Exception safety across thread boundaries.