Write A Program In Java To Develop Banking Application In Which User Deposits The Amount Rs 25000 And Then Start Withdrawing Of Rs 20000, Rs 4000 And It Throws Exception "Not Sufficient Fund" When User Withdraws Rs. 2000 Thereafter
Before demonstrate the program we will understand the concept of exception.
In java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions can be caused by various reasons such as user input errors, hardware failures, or resource exhaustion.
When an exception occurs, the java runtime system creates an exception object and throws it. This object contains information about the error that occurred, including its type and a detailed message.
To handle exceptions in your code, you can use a try-catch block. The try block contains the code that might throw an exception. If an exception is thrown within the try block, it is caught by the catch block that follows it. The catch block contains code that handles the exception and takes appropriate action.
Here’s an example:
try { // Code that might throw an exception} catch (ExceptionType e) { // Code to handle the exception}
In this example, if an exception of type exceptiontype is thrown within the try block, it will be caught by the catch block and handled appropriately.
Java also provides several built-in exception classes for common error conditions such as arithmeticexception, nullpointerexception, and ioexception. You can also create your own custom exceptions by extending one of the existing exception classes.
Here’s an example program that demonstrates how to create a simple banking application in Java that throws a custom “Not Sufficient Fund” exception:
class NotSufficientFundException extends Exception { public NotSufficientFundException(String message) { super(message); }}
class BankAccount { private double balance;
public BankAccount(double balance) { this.balance = balance; }
public void deposit(double amount) { balance += amount; }
public void withdraw(double amount) throws NotSufficientFundException { if (amount > balance) { throw new NotSufficientFundException("Not sufficient funds!"); } balance -= amount; }
public double getBalance() { return balance; }}
public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(0); account.deposit(25000);
try { account.withdraw(20000); System.out.println("Balance: " + account.getBalance());
account.withdraw(4000); System.out.println("Balance: " + account.getBalance());
account.withdraw(2000); System.out.println("Balance: " + account.getBalance()); } catch (NotSufficientFundException e) { System.out.println(e.getMessage()); } }}
Balance: 5000.0
Balance: 1000.0
Not sufficient funds!