1、异常

异常举例
BankAccount.h
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
#include <iostream>
#include <stdexcept>
class InsufficientFundsException : public std::runtime_error {
public:
InsufficientFundsException() : std::runtime_error("Insufficient funds for this operation.") {}
};
class BankAccount {
private:
std::string accountNumber;
double balance;
public:
BankAccount(const std::string& accNum) : accountNumber(accNum), balance(0.0) {}
void deposit(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Deposit amount must be positive.");
}
balance += amount;
std::cout << "Deposited: " << amount << ", New Balance: " << balance << std::endl;
}
void withdraw(double amount) {
if (amount > balance) {
throw InsufficientFundsException();
}
balance -= amount;
std::cout << "Withdrew: " << amount << ", New Balance: " << balance << std::endl;
}
double getBalance() const {
return balance;
}
std::string getAccountNumber() const {
return accountNumber;
}
};
#endif // BANK_ACCOUNT_H
Bank.h
#ifndef BANK_H
#define BANK_H
#include <iostream>
#include <map>
#include "BankAccount.h"
class AccountNotFoundException : public std::runtime_error {
public:
AccountNotFoundException(const std::string& accNum)
: std::runtime_error("Account not found: " + accNum) {}
};
class Bank {
private:
std::map<std::string, BankAccount> accounts;
public:
void createAccount(const std::string& accNum) {
accounts.emplace(accNum, BankAccount(accNum));
std::cout << "Account created: " << accNum << std::endl;
}
BankAccount& getAccount(const std::string& accNu