Skip to content
UniCircle
MediumCodingException handling

Bank account with a custom checked exception

Question JAVA-COD-105

Model a bank account that starts at balance 0 and processes q commands:

  • DEPOSIT x — add x. If x ≤ 0, print ERROR invalid amount.
  • WITHDRAW x — subtract x. If x ≤ 0, print ERROR invalid amount; if x is more than the balance, print ERROR insufficient funds and leave the balance unchanged.
  • BALANCE — print the balance.

In Java, report insufficient funds by throwing your own checked exception InsufficientFundsException from withdraw, and invalid amounts with IllegalArgumentException. The caller catches them and prints the messages. Successful deposits and withdrawals print nothing.

Constraints

  • 1 ≤ q ≤ 100000
  • −10^9 ≤ x ≤ 10^9

Input and output

Input
Line 1: q. Next q lines: one command each.
Output
One line for each BALANCE or error, in order.

Examples

Input 1

5
DEPOSIT 100
WITHDRAW 30
BALANCE
WITHDRAW 500
BALANCE

Output

70
ERROR insufficient funds
70

100 − 30 = 70; the 500 withdrawal fails and the balance stays 70.

Input 2

3
DEPOSIT -5
WITHDRAW 0
BALANCE

Output

ERROR invalid amount
ERROR invalid amount
0

Both amounts are invalid; the balance is still 0.

Show hints
  • A checked exception extends Exception (not RuntimeException) and must be declared with throws.
  • Validate before changing state so a failed withdrawal leaves the balance untouched.
Show the explanation

The design point is the exception hierarchy. InsufficientFundsException extends Exception is checked, so withdraw must declare throws InsufficientFundsException and every caller is forced to handle it — fitting for a business rule the caller should expect. Bad arguments are programmer errors, so the unchecked IllegalArgumentException fits. Check everything before changing the balance, so the object stays consistent when an exception is thrown. Use long for the balance to avoid overflow.

Original UniCircle question. Last reviewed 22 Oct 2026.