LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Programs · Question 2

Bank transfer with rollback using exceptions in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Implement transfer(from, to, amount) between accounts that debits first, then credits; if the credit fails (e.g. the target account is frozen), roll back the debit and rethrow. Show balances after successful and failed transfers.

Solution
main.cpp
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>

struct BankError : std::runtime_error { using std::runtime_error::runtime_error; };

struct Account {
    long balance = 0;
    bool frozen = false;
    void debit(long x) { if (x > balance) throw BankError("insufficient funds"); balance -= x; }
    void credit(long x) { if (frozen) throw BankError("target account frozen"); balance += x; }
};

void transfer(Account& from, Account& to, long amount) {
    from.debit(amount);
    try {
        to.credit(amount);
    } catch (...) {
        from.balance += amount;          // roll back the debit
        throw;                           // and let the caller know
    }
}

int main() {
    std::map<std::string, Account> bank{{"asha", {1000, false}}, {"ravi", {200, false}}, {"meena", {500, true}}};
    struct T { const char* from; const char* to; long amt; } ops[] = {{"asha", "ravi", 300}, {"ravi", "asha", 900}, {"asha", "meena", 100}};
    for (const auto& t : ops) {
        try {
            transfer(bank[t.from], bank[t.to], t.amt);
            std::cout << t.from << "->" << t.to << ' ' << t.amt << ": ok\n";
        } catch (const BankError& e) {
            std::cout << t.from << "->" << t.to << ' ' << t.amt << ": " << e.what() << '\n';
        }
    }
    for (const auto& [name, a] : bank) std::cout << name << '=' << a.balance << ' ';
    std::cout << '\n';
    return 0;
}

Output Verified by compiling and running

asha->ravi 300: ok
ravi->asha 900: insufficient funds
asha->meena 100: target account frozen
asha=700 meena=500 ravi=500

catch (...) with throw; adds a rollback step without deciding how the error is reported – the caller still receives the original BankError.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links