package com.zidingyi; public class NewException extends Exception { public NewException() { System.out.println("账户余额不足,无法完成取款"); } }
package com.zidingyi; public class Bank { //成员变量 private double yue; public double getYue() { return yue; } public void setYue(double yue) { this.yue = yue; } //成员方法 //存钱 public double cunqian(double cun) { yue+=cun; return yue; } //取钱 public void quqian(double qu) throws NewException { if(qu>yue) { System.out.println("取款金额为:"+qu); throw new NewException(); } else { yue-=qu; System.out.println("取款金额为:"+qu); } } public static void main(String[] args) { Bank b = new Bank(); b.cunqian(100); try { b.quqian(100); } catch (Exception e) { e.printStackTrace(); } System.out.println("账户余额为:"+b.yue); } }
以上情况是当取款金额小于等于账户余额时,如果我们的取款金额大于账户余额,则如下图: