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.
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.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 :
Here is complete example of how to create a user defined custom Exception in Java.
In this example we have anclass, 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 to handle this scenario.
This is Custom Exception class.In this class we have created two constructors for displaying error message.
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.
Now create a test class to test our implemented Custom Exception Class.
Current balance : 2800
Exception in thread "main" com.jwt.core.java.InSufficientFundException: Current balance 2800 is less than requested amount 3500