java Excption example

来源:互联网 发布:淘宝采集软件贵吗 编辑:程序博客网 时间:2024/06/05 03:16
public class ThrowException {

class InsufficientException extends Exception {
  private double amount;
  
  public InsufficientException(double amount) {
     this.amount = amount;
  }
  
  public double getAmount() {
     return amount;
  }
}

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 InsufficientException {
     if(amount <= balance) {
        balance -= amount;
     }else {
        double needs = amount - balance;
        throw new InsufficientException(needs);
     }
  }
  
  public double getBalance() {
     return balance;
  }
  
  public int getNumber() {
     return number;
  }
}

public static void main(String [] args) {
ThrowException throwE = new ThrowException();
ThrowException.CheckingAccount c = throwE.new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00); 
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
   e.printStackTrace();
}
}
}
0 0