班级: 姓名: 学号: 成绩
异常
实验目的: 1. 理解异常现象及异常的抛出机制 2. 掌握异常抛出时的处理机制 3. 掌握自定义异常的方法 4. 能够掌握在方法代码中添加抛出异常的处理 实验要求和过程 1. public class TestApp{ public static void main(String[] args){ try{ int i = 0; int j = 1 / i; String myname=null; if(myname.length()>2) System.out.print(“1”); }catch(NullPointerException e){ System.out.print(“2”); }catch(Exception e){ System.out.print(“3”); } } } 分析上述程序运行后的输出的结果和原因。 输出结果是:3 原因:int j = 1 / i;这句话除0异常,catch并没有相对应Exception e子类捕获错误,所以输出Exception中语句,并结果程序。 2. 下面是一个名称为NegativeAmountException的自定义异常类,表示一个不正常的银行账目事件类。填充下面的语句,完成该类的编写。 class NegativeAmountException _extends__ _Expection___{ //NegativeAmountException异常:用消息s创建异常 NegativeAmountException(String s){ super(s); } } class Account{ double balance; //构造函数,余额为0; public Account(){ balance = 0; } //构造函数,余额为n,如果初始余额小于0抛出异常 public Account( double n) throws NegativeAmountException{ if(n>0){ this.balance = n; }else { __throw new_NegativeAmountException(“余额小于0异常”); } } //查询余额方法,返回当前余额 public double getBalance(){ return this.balance; } //存款方法,存款数额amount; 如果存款数目小于0抛出异常 public void deposit(double amount)_ throws NegativeAmountException _{ if(amount>=0){ balance+=amount; }else { throw new NegativeAmountException(\"存款金额小于0异常!\"); } } //取款方法,取款数额amount; 如果取款数目小于0抛出异常 public void withdraw(double amount)__ throws NegativeAmountException { if(amount<0){ throw new NegativeAmountException(\"取款金额小于0异常!\"); }else if(balance 0) { this.balance = n; } else { throw new NegativeAmountException(\"余额小于0异常\"); } } // 查询余额方法,返回当前余额 public double getBalance() throws BlockedException{ if(satstus==\"blocked\") throw new BlockedException(\"冻结\"); else return this.balance; } // 存款方法,存款数额amount; 如果存款数目小于0抛出异常 public void deposit(double amount) throws NegativeAmountException,BlockedException{ if(satstus==\"blocked\"){ throw new BlockedException(\"冻结\"); }else if (amount >= 0) { balance += amount; } else { throw new NegativeAmountException(\"存款金额小于0异常!\"); } } // 取款方法,取款数额amount; 如果取款数目小于0抛出异常 public void withdraw(double amount) throws NegativeAmountException,BlockedException{ if(satstus==\"blocked\"){ throw new BlockedException(\"冻结\");} else if (amount < 0) { throw new NegativeAmountException(\"取款金额小于0异常!\"); } else if (balance < amount) { throw new NegativeAmountException(\"取款金额大于余额异常!\"); } else { balance -= amount; } } } package shiyan10; public class TestNegativeAmountException { public static void main(String args[]){ try { Account a1 = new Account(); a1.setSatstus(\"反对\"); a1.deposit(100); a1.setSatstus(\"blocked\"); // a1.withdraw(-100); a1.withdraw(30); System.out.println(\"balance of a1:\" + a1.getBalance()); // Account a2 = new Account(-10); // // a2 = new Account(10); // a2.deposit(-20); // a2.withdraw(-10); // a2.withdraw(30); // a2.withdraw(3); // System.out.println(\"balance of a1:\" + a2.getBalance()); } catch (NegativeAmountException e) { e.printStackTrace(); } catch (BlockedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } 评语: 教师签字: 日期: 年 月 日