Answer to Question #183705 in C++ for VARUN

Question #183705

 Templates and Exception Handling


Design simple class BankAccount. If amount to be withdrawn is greater than balance, throw “Insufficient Balance” exception.


1
Expert's answer
2021-04-20T16:19:42-0400
#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;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS