package testExpection; //public修饰的类必须为文件名 public class TestException { public static void main(String[] args) { Account a = new Account(10086);//前为类名 后为构造函数 System.out.println("存款500");//必须双引号 a.deposit(500); //开始异常块---使用了异常的函数 需要放到try_catch块中 try { System.out.println("取款100"); a.withdraw(100); System.out.println("取款1000"); a.withdraw(1000); } catch (InsufficientFundsExpection e) { //具体的处理异常的逻辑放这里 至于有哪些异常 在这个函数(可能多个)中定义 函数内部仅仅定义异常类型 不规定这样怎么处理 System.out.println("取款失败,欠缺"+ e.getNeed()); //此处可以调用这个异常定义的方法 e.printStackTrace();//trace的方法 } //catch块可以写多个 //finally块可选 } } class Account{ private double balence; private int card_number; public Account(int card_number) { this.card_number=card_number; } //存钱 public void deposit(double amount) { balence+=amount; } public double getBalence() { return balence; } public int getCardNumber() { return card_number; } //和之前php的区别 php一般是在这个函数里 如果不符合要求return false 或者余额不足 成功返回余额 或者直接die(errmeg)中止运行 //而java是通过另一个方法getBalence 去获取这个值 可能是因为php通常是从数据库中拿东西 感受不到 public void withdraw(double amount) throws InsufficientFundsExpection { //是在函数处写用哪个异常类 if(amount<=balence) { balence -=amount; System.out.println("余额为:"+ balence); }else { double need = amount-balence; throw new InsufficientFundsExpection(need);//此处throw写具体的构造函数 } } } //如果希望写一个检查性异常类,则需要继承 Exception 类。 //如果你想写一个运行时异常类,那么需要继承 RuntimeException 类 class InsufficientFundsExpection extends Exception{ private double need; public InsufficientFundsExpection(double need) { this.need=need; } public double getNeed() { return need; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)