chapter17ExceptionHandling选编.ppt

* * * * * * * * * * * * * * * public class TestBankCount { public static void main(String[] args) { Scanner s = new Scanner(System.in); double money = s.nextDouble(); BankAccount bankAccount = new BankAccount(1000); bankAccount.getMoney(money); } } 以上实现过程,在BankAccount类描述的取款动作中,有可能 发生异常,利用throw关键字手动抛出异常,并且利用try catch 对抛出的异常自己进行处理。 也可以在抛出后,利用throws关键字将异常继续向外抛出,由 调用该方法的程序利用try catch来处理。 public class BankAccount { private double moneyCount;//用来记录当前账号上的余额 public BankAccount(double moneyCount){ this.moneyCount = moneyCount; } public void getMoney(double money) throws InsufficientMoneyException{ if (money moneyCount) { throw new InsufficientMoneyException(钱不够了!); } if (money 0) { throw new InsufficientMoneyException(请输入正数!); } System.out.println(取款成功!); } } public class TestBankCount { public static void main(String[] args) { Scanner s = new Scanner(System.in); double money = s.nextDouble(); BankAccount bankAccount = new BankAccount(1000); try { bankAccount.getMoney(money); } catch (InsufficientMoneyException e) { System.out.println(e); } }} 总结 异常是运行时发生的错误 可以使用 try、catch、throw、throws 和 finally 来管理 Java 异常处理。要监控的程序语句包含在 try 块内catch 块中的代码用于捕获和处理异常。在方法返回之前绝对必须执行的代码应放置在 finally 块中 要手动引发异常,使用关键字 throw。任何被抛到方法外部的异常都必须用 throws 子句指定 自定义异常的编写和使用 以下内容学生了解(软件大赛时需要) 17.3 When to Use Exceptions When? (Page.590)Use it when you have to deal with unexpected error conditions. Do not use a try-catch block to deal with simple、expected situations. (Page.591)The point is not to abuse exception handling as a way to deal with a simple logic test. if (refVar != null) System.out.println(refVar.toString()); else System.out.println(refVar is null); try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println(refVar is null); } 17.4 Exceptions and Exception Types Object Throwable Exception Error RuntimeException 记忆:RuntimeException中常见的有: Ar

文档评论(0)

1亿VIP精品文档

相关文档