




已阅读5页,还剩31页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第 4 章 异常,北京大学计算机系 代亚非,2,第4章 异常,4.1 异常的概念 4.2 异常的分类 4.3 捕获异常 4.4 声明异常 4.5 抛出异常 4.6 创造自己的异常 4.7 总结,3,4.1 异常的概念,什么是异常? 异常实际上是程序中错误导致中断了正常的指令流的一种事件. 没有处理错误的程序: read-file openTheFile; determine its size; allocate that much memory; closeTheFile; ,4,4.1 异常的概念,以常规方法处理错误 openFiles; if (theFilesOpen) determine the lenth of the file; if (gotTheFileLength) allocate that much memory; if (gotEnoughMemory) read the file into memory; if (readFailed) errorCode=-1; else errorCode=-2; else errorCode=-3; else errorCode=-4 ; else errorCode=-5;,5,4.1 异常的概念,观察前面的程序你会发现大部分精力花在出错处理上了. 只把能够想到的错误考虑到,对以外的情况无法处理 程序可读性差 出错返回信息量太少,6,4.1 异常的概念,用异常的形式处理错误 read-File; try openTheFile; determine its size; allocate that much memory; closeTheFile; catch(fileopenFailed) dosomething; catch(sizeDetermineFailed) dosomething; catch(memoryAllocateFailed) dosomething; catch(readFailed) dosomething; catch(fileCloseFailed) dosomething; ,7,4.1 异常的概念,和传统的方法比较异常的优点: 1.把错误代码从常规代码中分离出来 2. 把错误传播给调 用堆栈 3. 按错误类型和 错误差别分组 4. 系统提供了对于一些无法预测的错误的捕获和处理 5. 克服了传统方法的错误信息有限的问题,8,4.1 异常的概念,.,class ExcepTest public void main(String args) int b=0; int a; try a=4/b; catch(ArithmeticException e) System.out.println(“divided by 0”); ,try URL url=new URL(/”,”hit.gif”); catch(MalformedURLEception e) badURL=true; repaint();,9,4.2 异常的分类,异常是一个对象,它继承自Throwable类,所有的Throwable类的子孙类所产生的对象都是例外. Error:由Java虚拟机生成并抛出,Java程序不做处理. Runtime Exception(被0除等系统错误,数组下标超范围):由系统检测, 用户的Java 程序可不做处理,系统将它们交给缺省的异常处理程序. Exception(程序中的问题,可预知的): Java编译器要求Java程序必须捕获或声明所有的非运行时异常 throw:用户自己产生异常,10,4.2 异常的分类,.,Throwable,Error,Exception,RuntimeException,缺省的异常 处理程序,由用户捕获或 声明并处理,不做处理,用户自己产生的异常,要处理,11,4.3 捕获异常,捕获并处理异常 try /接受监视的程序块,在此区域内发生 /的异常,由catch中指定的程序处理; catch(要处理的异常种类和标识符) /处理异常; catch(要处理的异常种类和标识符) /处理异常; ,12,4.3 捕获异常,常见的异常 ArithmeticException ArrayIndexOutOfBandsException ArrayStoreException IOException FileNotFoundException NullPointerException MalformedURLException NumberFormatException OutOfMemoryException,如果在使用能够产生异常的方法而没有捕获和处理,将不能通过编译,13,4.3 捕获异常,例:编写Java程序,包含三种异常 算术异常, 字符串越界,数组越界 观察输出信息: 每个异常对象可以直接给出信息,14,4.3 捕获异常,class first_exception public static void main(String args) char c; int a,b=0;int array=new int7; String s=“Hello“;,try a=1/b; catch(ArithmeticException ae) System.out.println(“Catch “+ae);,try array8=0; catch(ArrayIndexOutOfBoundsException ai) System.out.println(“Catch “+ai);,try c=s.charAt(8); catch(StringIndexOutOfBoundsException se) System.out.println(“Catch “+se);,15,4.3 捕获异常,一定会执行的程序块-finally 异常处理的统一出口 try /常规的代码; catch() /处理异常 finally /不论发生什么异常(或者不发生任何异常),都要执行的部分; ,16,4.3 捕获异常,finally在文件处理时非常有用 try 对文件进行处理的程序; catch(IOException e) /对文件异常进行处理; finally 不论是否发生异常,都关闭文件; ,17,4.4 声明异常,一个方法不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明异常. 声明异常的方法 在产生异常的方法名后面加上要抛出(throws)的异常的列表 void compute(int x)throws ArithmeticException returnType methodName(parameterlist) throws exceptionList,18,4.4 声明异常,例:若因某种原因不想在创建URL的方法中处理异常,public method1() int x; try x=System.in.read(); compute(x); catch(IOException ioe) System.out.println(“read error”); catch(ArithmeticException e) System.out.println(“devided by 0”); ,public int compute(int x) throws ArithmeticException e) return z=100/x;,19,4.4 声明异常,20,4.4 声明异常,例:说出程序执行结果 public class exception1 void Proc(int sel) throws ArithmeticException, ArrayIndexOutOfBoundsException System.out.println(“In Situation“ + sel ); if (sel=0) System.out.println(“no Exception caught“); return; else if(sel=1) int iArray=new int4; iArray10=3; ,21,4.4 声明异常,public static void main(String args) try Proc(0); Proc(1); catch(ArrayIndexOutOfBoundsException e) System.out.println(“Catch“+e); ,c:jview throwsException In Situation 0 no Exception caught In Situation 1 Catch java.lang.ArrayIndexOutOfBoundsException:10,22,4.5 抛出异常,抛弃异常: 不是出错产生,而是人为地抛出 throw ThrowableObject; throw new ArithmeticException(); 例:编写程序人为抛出(JavaThrow.prj) ArithmeticException, ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException,A method,Exception,Another method,throw,caught,23,4.5 抛出异常,class JavaThrow public static void main(String args) ,try throw new ArithmeticException(); catch(ArithmeticException ae) System.out.println(ae); ,try throw new ArrayIndexOutOfBoundsException(); catch(ArrayIndexOutOfBoundsException ai) System.out.println(ai); ,try throw new StringIndexOutOfBoundsException(); catch(StringIndexOutOfBoundsException si) System.out.println(si); ,24,4.6 创造自己的异常,不是由Java系统监测到的异常(下标越界,被0-除等),而是由用户自己定义的异常. 用户定义的异常同样要用try-catch捕获,但必须由用户自己抛出 throw new MyException. 异常是一个类,用户定义的异常必须继承自Throwable或Exception类,建议用Exception类.,25,4.6 创造自己的异常,形如: class MyException extends Exception .; 例1 :计算两个数之和,当任意一个数超出范围时,抛出自己的异常,public class NumberRangeException extends Exception public NumberRangeException(String msg) super(msg); ,26,4.6 创造自己的异常,.,public boolean action(Event evt, Object arg) try int answer = CalcAnswer(); answerStr = String.valueOf(answer); catch (NumberRangeException e) answerStr = e.getMessage(); repaint(); return true; ,27,4.6 创造自己的异常,.,public int CalcAnswer() throws NumberRangeException int int1, int2; int answer = -1; String str1 = textField1.getText(); String str2 = textField2.getText(); try int1 = Integer.parseInt(str1); int2 = Integer.parseInt(str2); if (int1 20) | (int2 20) NumberRangeException e = new NumberRangeException (”Numbers not within the specified range.“); throw e; answer = int1 + int2; catch (NumberFormatException e) answerStr = e.toString(); return answer; ,28,4.6 创造自己的异常,例2 :在定义银行类时,若取钱数大于余额则作为异常处理(InsufficientFundsException). 思路:产生异常的条件是余额少于取额, 因此是否抛出异常要判断条件 取钱是withdrawal方法中定义的动作,因此在该方法中产生异常. 处理异常安排在调用withdrawal的时候,因此withdrawal方法要声明异常,由上级方法调用 要定义好自己的异常类,29,4.6 创造自己的异常,.,class Bank double balance; public void deposite(double dAmount) if(dAmount0.0) balance+=dAmount; public void withdrawal(double dAmount) throws InsufficientFundsException if (balancedAmout) throw new InsufficientFundsException(this,dAmount); balance=balance-dAmount; public void show_balance() System.out.println(“The balance is “+(int)balance); ,30,4.6 创造自己的异常,public class ExceptionDemo public static void main(String args) try Bank ba=new Bank(50); ba.withdrawal(100); System.out.println(“Withdrawal successful!”); catch(Exception e) System.out.println(e.toString(); ,31,4.6 创造自己的异常,.,public class InsufficientFundsException extends Exception private Bank excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; public String excepMesagge() String str=“The balance”+ excepbank.showBalance()+ “The withdrawal was”+excepAmount; return str; ,32,4.7 小结,1.一般格式:正常程序和出错处理分离开来 try Java statement; catche(ExceptionType1 ExceptionObject) Exception1 handling; catche(ExceptionType2 Excep
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年桂林市火炬中学招聘考试试题(含答案)
- 2025年广西河池学院招聘教职人员工作人员考试笔试试题(含答案)
- 北京知名财务知识培训班课件
- 儿科N0-N1季度理论考试题(含答案)
- 2024年甘肃省公务员考试申论真题(含答案)
- 树洞里秘密课件
- 护理安全隐患及防范措施知识考试练习试题(附答案)
- 安生生产管理单选题多选题练习测试题(含答案)
- 2025年施工员之装修施工基础知识考试题库含答案【预热题】
- 2025《母婴保健法》必考题库及参考答案
- 2025年e答网护士三基考试试题及答案
- 信息平台造价管理办法
- DG-TJ08-2202-2024 建筑信息模型技术应用标准(城市轨道交通)
- 2025年度学校国际交流合作计划
- 2025年注册土木工程师专业基础考试题(附答案)
- 安全管理目标及责任书
- 阀门配送方案模板(3篇)
- 激光切割安全操作规程
- 海事管理培训课件
- 《曾国藩传》读书分享课件
- 十五五林业发展规划(完整版)
评论
0/150
提交评论