所以下面的定义中,前子类1-3重写和子类5-7都是有效的,但子类4重写是错误的。
父类:method() throws IOException {} 子类1:method() throws {} 子类2:method() throws IOException {} 子类3:method() throws FileNotFoundException {} 子类4:method() throws Exception {} 子类5:method() throws RuntimeException {} 子类6:method() throws IOException,RuntimeException {} 子类7:method() throws IOException,ArithmeticException {} 自定义异常异常是类,当产生异常时会构建此类的异常对象。
自定义异常时需要考虑异常类的构造方法是否接参数,参数需要如何处理实现怎样的逻辑。
自定义的异常一般都从Exception继承。
例如下面定义了一个银行卡存、取钱时的程序,其中自定义了一个Exception类错误。
// User Define Exception class OverDrawException extends Exception { private double amount; public OverDrawException(double amount) { this.amount = amount; } public OverDrawException(String message) { super(message); } public double getAmount() { return amount; } } // Card class class Card { //cardNum:卡号,balance:余额 private String cardNum; private double balance; Card(String n,double b) { this.cardNum = n; this.balance = b; } //方法:存钱 public void cunQian(double n) { balance += n; } //方法:取钱 public void quQian(double n) throws OverDrawException { if (n <= this.balance) { balance -= n; } else { double need = n - balance; throw new OverDrawException(need); } } //方法:返回余额 public double getBalance() { return this.balance; } } public class SuanZhang { public static void main(String [] args) { try { Card card = new Card("62202",300); System.out.println("卡里余额:" + card.getBalance()); //存钱 card.cunQian(200); System.out.println("余额:" + card.getBalance()); //取钱 card.quQian(600); System.out.println("余额:" + card.getBalance()); } catch (OverDrawException e) { System.out.println(e); System.out.println("抱歉!您的余额不足,缺少:" + e.getAmount()); } } }