Q.Write a Java program to create an account class. Define appropriate constructor for this class. Define and implement method to display account balance and withdraw money. Show appropriate message if there is an attempt to withdraw money which may lead to account balance, less than minimum amount required in account. Make necessary assumptions required.

ANS. 

Introduction :

Sometimes it is required to develop meaningful exceptions based on application requirements.For example suppose you have one savings account in any Bank and you have 50 dollars in your account.Suppose you attempted to withdraw 60 dollars from your account. In java you can handle this scenario by using ArithmeticException.But this Exception is not meaningful as a user point of view. You need to display some error message related to insufficient fund.
To have good meaning, we can create our own exception. If an exception like InSufficientFundException exists, it well suits for the problem of insufficient funds.
We can create our own exceptions by extending ‘Exception’ class.

Steps to implement User defined Exception class :

  • The user defined exception class must extend from java.lang.Exception or java.lang.RunTimeException class. Also note that RuntimeException and its sub classes are not checked by the compiler and need not be declared in the method’s signature.
  • While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception.
  • Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.
  • Every user defined exception class parametrized Constructor must called parametrized Constructor of either java.lang.Exception or java.lang.RunTimeException class by using super(string parameter always).
Here is complete example of how to create a user defined custom Exception in Java.
In this example we have an Account class, which is representing a bank account where you can deposit and withdraw money, but what will happen if you want to withdraw money which exceed your bank balance? You will not be allowed, and this is where user defined exception comes into picture. We have created a custom exception called InSufficientFundException to handle this scenario.

InSufficientFundException.java

This is Custom Exception class.In this class we have created two constructors for displaying error message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.jwt.core.java;
 
public class InSufficientFundException extends RuntimeException {
 
    private String message;
 
    public InSufficientFundException(String message) {
        this.message = message;
    }
 
    public InSufficientFundException(Throwable cause, String message) {
        super(cause);
        this.message = message;
    }
 
    public String getMessage() {
        return message;
    }
 
}

Account.java

In this class we have created two methods withdraw and deposit.Initial Balance of Account is 3000 dollars.Withdraw method parameter is amount and that amount we are subtracting from initial balance. If amount passes is greater than initial balance, it will throw Custom Exception InSufficientFundException,else it will calculate new balance by subtracting amount from initial balance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.jwt.core.java;
 
public class Account {
 
    private int balance = 3000;
 
    public int balance() {
        return balance;
    }
 
    public void withdraw(int amount) throws InSufficientFundException {
        if (amount > balance) {
            throw new InSufficientFundException(String.format(
                    "Current balance %d is less than requested amount %d",
                    balance, amount));
        }
        balance = balance - amount;
    }
 
    public void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException(String.format(
                    "Invalid deposit amount %s", amount));
        }
    }
 
}

Test.java

Now create a test class to test our implemented Custom Exception Class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.jwt.core.java;
 
public class Test {
 
    public static void main(String args[]) {
        Account acct = new Account();
        System.out.println("Current balance : " + acct.balance());
        System.out.println("Withdrawing $200");
        acct.withdraw(200);
        System.out.println("Current balance : " + acct.balance());
        acct.withdraw(3500);
 
    }
 
}

Output

Current balance : 2800
Exception in thread "main" com.jwt.core.java.InSufficientFundException: Current balance 2800 is less than requested amount 3500
at com.jwt.core.java.Account.withdraw(Account.java:13)
at com.jwt.core.java.Test.main(Test.java:11)


LEAVE A REPLY

Please enter your comment!
Please enter your name here