019-006-007

Creating and Using Custom Exceptions

Medium

Problem Description

Creating and Using Custom Exceptions

In this problem, you will create a program that implements a custom InsufficientFundsException class and a BankAccount class to validate withdrawals and handle exceptions for insufficient balance.

Learning Objective: Understand how to create custom exception classes and implement exception handling for business logic

Overview

Create a custom exception InsufficientFundsException to represent insufficient balance in a bank account and use it for withdrawal validation.

Specifications

InsufficientFundsException Class (extends Exception)

  • Field: double shortfall (the deficit amount)
  • Constructor: accepts a message and shortfall, calls super(message) to initialize the superclass
  • Method: getShortfall() returns the shortfall amount

BankAccount Class

  • Field: double balance
  • Constructor: accepts initial balance
  • Method: withdraw(double amount) performs withdrawal
    • If insufficient balance (amount > balance), throws InsufficientFundsException with message "Balance insufficient for withdrawal" and the shortfall amount
    • On success, deducts from balance
  • Method: getBalance() returns the balance

Main Class

  • static void withdraw(double initialBalance, double amount) throws InsufficientFundsException
    • Creates a BankAccount with the given initial balance and calls withdraw(amount)
    • Propagates InsufficientFundsException if balance is insufficient
  • Include a main method (for compilation)

Test Method

Each test case calls Main.withdraw(double, double) directly and verifies:

  • Valid withdrawals (e.g., 300.0 from balance 1000.0) do not throw an exception
  • Invalid withdrawals (e.g., 1500.0 from balance 1000.0) throw InsufficientFundsException with message "Balance insufficient for withdrawal"

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up