Exception Handling










InsufficientFundsException.java
package Bank_Concept;

public class InsufficientFundsException extends Exception {
private double amount;

public InsufficientFundsException(double amount) {
this.amount = amount;
}

public double getAmount() {
return amount;
}
}//class InsufficientFundsException

CheckingAccount.java
package Bank_Concept;

public class CheckingAccount {
private double balance;
private int number;

public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= balance) {
balance -= amount;
} else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

// withdraw()

public double getBalance() {
return balance;
}

public int getNumber() {
return number;
}
}// class

BankDemo.java
package Bank_Concept;

import java.util.Scanner;

public class BankDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking Account Number as Input from the user OK:-
System.out.println("Enter the Account Number:");
int input = sc.nextInt();
CheckingAccount c = new CheckingAccount(input);

System.out.println();
System.out.println("Depositing: $500...");
c.deposit(500.00);
System.out.println("Now, The Acc balance is: " + c.getBalance());
System.out.println("For the account number of: " + c.getNumber());
try {

System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("Now, The Acc balance is: " + c.getBalance());
System.out.println("For the account number of: " + c.getNumber());

// Again Withdrawing:-
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
System.out.println("Now, The Acc balance is: " + c.getBalance());
System.out.println("For the account number of: " + c.getNumber());

} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $:" + e.getAmount());
System.out.println("For the account number of: " + c.getNumber());
System.out.println();
e.printStackTrace();
}

}// main()
}

o/p:-
Enter the Account Number:
25

Depositing: $500...
Now, The Acc balance is: 500.0
For the account number of: 25

Withdrawing $100...
Now, The Acc balance is: 400.0
For the account number of: 25

Withdrawing $600...
Sorry, but you are short $:200.0
For the account number of: 25

Bank_Concept.InsufficientFundsException
at Bank_Concept.CheckingAccount.withdraw(CheckingAccount.java:20)
at Bank_Concept.BankDemo.main(BankDemo.java:27)

No comments:

Post a Comment