CodeBlanks Logo Icon CodeBlanks

Summary - Exceptions

Combine try/catch and a custom exception to write a bank account class.

Summary: Bank account

In this summary we will combine try/catch, throw and a custom exception to build a small bank account class. The Account class holds deposit and withdraw methods; if the balance is insufficient, an InsufficientFunds exception is thrown.

The plan: first derive the InsufficientFunds class from std::exception, then define the Account class with a balance member. The withdraw method throws if the amount exceeds the balance; the caller catches it with try/catch and reads the message via e.what(). This combines the exception tools in a real scenario.

Practice InsufficientFunds and withdraw

Add #include <stdexcept>. Define class InsufficientFunds : public std::exception; in a public: block write const char* what() const noexcept override { return "insufficient balance"; }. In main, add try { throw InsufficientFunds(); } catch (const std::exception& e) { cout << e.what() << endl; }.

Starter code

main.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

// Define the InsufficientFunds class

int main() {
    // in try throw, in catch print the message
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

class InsufficientFunds : public std::exception {
public:
    const char* what() const noexcept override {
        return "insufficient balance";
    }
};

int main() {
    try {
        throw InsufficientFunds();
    } catch (const std::exception& e) {
        cout << e.what() << endl;
    }
    return 0;
}

Expected output

insufficient balance

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each tool with its job

Term Meaning
try risky operation
throw throws an exception
InsufficientFunds custom exception

2 What should the withdraw method do when the balance is insufficient?

  • Crash
  • Throws InsufficientFunds Correct answer
  • Returns 0
  • Ignores

Explanation: On insufficient balance, InsufficientFunds is thrown.

3 Fill in the blank: derivation

Question
class InsufficientFunds : public ____ {
public:
    const char* what() const noexcept override;
};
Answer
class InsufficientFunds : public std::exception {
public:
    const char* what() const noexcept override;
};

Explanation: std::exception is used as the base class.

All lessons in Beginner