Custom Exception example for BankAccount
class BankAccount {
int accountNumber;
double accountBalance;
public BankAccount(int accountNumber, double accountBalance) {
this.accountNumber = accountNumber;
this.accountBalance = accountBalance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getAccountBalance() {
return accountBalance;
}
public boolean withdraw (double amount) throws WithdrawLimitException
{
if( amount > accountBalance)
{
throw new WithdrawLimitException("Withdrawing Amount is more than Balance amount.. ");
// return false;
}
else
{
accountBalance -= amount;
return true;
}
}
public boolean deposit(double amount)
{
if( amount < 0.0)
{
return false; // can not deposit a negative amount
}
else
{
accountBalance += amount;
return true;
}
}
}
class WithdrawLimitException extends Exception {
public WithdrawLimitException(String message) {
super(message);
}
}
// Application Class
public class BankAccountMainExample {
public static void main(String[] args) {
BankAccount ba = new BankAccount(101,10000);
if (!(ba.deposit(20000))) {
System.out.println("Negative amount can not be deposited..");
}
try {
ba.withdraw(70000);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Account balance : "+ ba.getAccountBalance());
}
}
Comments
Post a Comment