Templates and Exception Handling
Design simple class BankAccount. If amount to be withdrawn is greater than balance, throw “Insufficient Balance” exception.
#include <exception>
#include <iostream>
#include <string>
using namespace std;
class InsufficientBalanceException : public exception
{
public:
virtual const char* what() const noexcept override
{
return "Insufficient Balance Exception";
}
};
class BankAccount
{
private:
double balance;
public:
void setBalance(double balance)
{
this->balance = balance;
}
double getBalance()
{
return balance;
}
void withdraw(double money)
{
setBalance(balance - money);
}
};
int main()
{
BankAccount bankAccount;
bankAccount.setBalance(500);
try
{
cout << "Current balance: " << bankAccount.getBalance() << endl;
cout << "How much you want to withdraw? ";
double money;
cin >> money;
if(money > bankAccount.getBalance())
throw InsufficientBalanceException();
else
{
bankAccount.withdraw(money);
cout << money << " withdrawn successfully" << endl;
cout << "Current balance: " << bankAccount.getBalance() << endl;
}
}
catch(InsufficientBalanceException& e)
{
cout << e.what() << endl;
}
}
Comments
Leave a comment