* * * * * * * * * * * * * * * 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
您可能关注的文档
最近下载
- 2025年山东药品食品职业学院高职单招综合素质考试参考题库及答案解析.docx VIP
- (高清版)DB4409∕T 24-2021 《奇楠沉香扦插技术规程》.docx VIP
- 2026年广东中考生物命题趋势预测试卷(附答案解析).docx VIP
- 北京市2025年高考:《英语》考试真题(含答案).pdf VIP
- 世界金融史:泡沫、战争与股票市场([日]板谷敏彦 著).pdf VIP
- 2025年北京央教湘岳假期寒假作业七年级英语人教版答案.pdf VIP
- 明月海藻实习素材.doc VIP
- 死因监测工作例会的制度.doc VIP
- 《墙面石材干挂(背栓式)施工工艺》.docx VIP
- 老年人营养不良的评估(老年人能力评估课件).ppt
原创力文档

文档评论(0)