public class MeiQianException extends Exception {//它的父类是异常 /** * 1、所有的异常的都是Throwable的子类 * 2、如果写一个运行时异常,需要继承RuntimeException * 3、如果要写一个编译时异常,继承Exception * 未雨绸缪,提前检查 */ public MeiQianException(String message) { super(message); } }
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class AccountManager { //余额 private Double balance; public AccountManager(Double balance){ this.balance = balance; } public void deposit(Double money){//存钱的方法 balance = balance + money ; System.out.println("银行卡里面还有:"+balance); } public void withdraw(Double money) throws MeiQianException {//取钱 if (balance >= money) { balance = balance - money; System.out.println("银行卡还有:"+balance); } else { Double needMoney = money - balance; throw new MeiQianException("余额不足,还差:" + needMoney);//抛出异常 } } public static void main(String[] args) { AccountManager accountManager = new AccountManager(800.0);//这是银行里面的余额 try { accountManager.withdraw(1000.0);//这句话可能会有异常, } catch (MeiQianException e) {//有的话就捕捉 e.printStackTrace(); } } }