Object-oriented programming · 21 / 26 Exercise Medium

Bank account with exceptions

Objective

A class protects its data: the balance only changes through methods that check that the operation is valid and, if it is not, warn with an exception.

Instructions

  • Define the exception InsufficientBalance and the class Account, with the balance in a private attribute _balance (it starts at 0), a read-only property balance and a counter operations of operations carried out.
  • The method deposit_money(amount) adds the amount and withdraw_money(amount) subtracts it. If the amount is not greater than 0, they raise ValueError with the message invalid amount; if more is withdrawn than there is, InsufficientBalance with insufficient balance.
  • Read n and then n lines with deposit or withdraw, and the quantity. After each successful operation show Balance: x; if it fails, show Error: message with the exception message.
  • At the end show Final balance: x and Operations: m (only successful operations count).
Input
4
deposit 100
withdraw 30
withdraw 100
deposit 0
Output
Balance: 100
Balance: 70
Error: insufficient balance
Error: invalid amount
Final balance: 70
Operations: 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise