Implement a Class BankAccount with two members account_number and balance.It also has two member methods createAccount(acc_num,bal) and withdraw(amount). Implement an Exception class which handles the following exceptions.
Write a ExDemoClass with main() that tests the same.Include a finally block which prints “In finally block”.
- MinimumBalanceExcpetion: If an account is started with an amount less than the minimum balance,throw this exception.
- InSufficientFundException: If a person tries to withdraw an amount more than his/her actual balance, throw this exception.
Write a ExDemoClass with main() that tests the same.Include a finally block which prints “In finally block”.
SOLUTION:
import java.util.Scanner; public class Question3ExDemoClass { public static void main(String[] args) { int ac,bal,amt; //Creating Scanner object Scanner input=new Scanner(System.in); System.out.println("Enter account number and balance"); ac=input.nextInt(); bal=input.nextInt(); try { BankAccount b1=new BankAccount(); b1.createAccount(ac, bal); System.out.println("Enter amount to withdraw"); amt=input.nextInt(); b1.withdraw(amt); } catch(MinimumBalanceException minimumBalanceException){ System.out.println(minimumBalanceException.getLocalizedMessage()); } catch(InsufficientFundException insufficientFundException){ System.out.println(insufficientFundException.getMessage()); } finally{ System.out.println("In finally block."); } } } class BankAccount { private int accountNumber; private int balance; void createAccount(int a,int b) throws MinimumBalanceException { if(b<1000) throw new MinimumBalanceException("Please deposit more Money."); else { this.accountNumber=a; this.balance=b; } } void withdraw(int amount) throws InsufficientFundException { if(amount>this.balance) throw new InsufficientFundException("You do not have enough cradit balance."); else this.balance-=amount; } } class MinimumBalanceException extends Exception { public MinimumBalanceException(String s) { super(s); } } class InsufficientFundException extends Exception{ public InsufficientFundException(String s) { super(s); } }
No comments:
Post a Comment