




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、第第 4 章章 异常异常n北京大学计算机系北京大学计算机系n代亚非代亚非2第第4章章 异常异常n4.1 4.1 异常的概念异常的概念n4.2 4.2 异常的分类异常的分类n4.3 4.3 捕获异常捕获异常n4.4 4.4 声明异常声明异常n4.5 4.5 抛出异常抛出异常n4.6 4.6 创造自己的异常创造自己的异常n4.7 4.7 总结总结34.1 异常的概念异常的概念n什么是异常什么是异常? 异常实际上是程序中错误导致中断了正异常实际上是程序中错误导致中断了正常的指令流的一种事件常的指令流的一种事件.n没有处理错误的程序没有处理错误的程序: read-file read-file open
2、TheFile; openTheFile; determine its size; determine its size; allocate that much memory; allocate that much memory; closeTheFile; closeTheFile; 44.1 异常的概念异常的概念n以常规方法处理错误以常规方法处理错误 openFiles;openFiles; if (theFilesOpen) if (theFilesOpen) determine the lenth of the file; determine the lenth of the file
3、; if (gotTheFileLength) if (gotTheFileLength) allocate that much memory; allocate that much memory; if (gotEnoughMemory) if (gotEnoughMemory) read the file into memory; read the file into memory; if (readFailed) errorCode=-1; if (readFailed) errorCode=-1; else errorCode=-2; else errorCode=-2; else e
4、rrorCode=-3; else errorCode=-3; else errorCode=-4 ; else errorCode=-4 ; else errorCode=-5; else errorCode=-5; 54.1 异常的概念异常的概念n观察前面的程序你会发现大部分精力花在观察前面的程序你会发现大部分精力花在出错处理上了出错处理上了.n只把能够想到的错误考虑到只把能够想到的错误考虑到,对以外的情况对以外的情况无法处理无法处理n程序可读性差程序可读性差n出错返回信息量太少出错返回信息量太少64.1 异常的概念异常的概念n用异常的形式处理错误用异常的形式处理错误read-File;r
5、ead-File; try try openTheFile;openTheFile; determine its size; determine its size; allocate that much memory; allocate that much memory; closeTheFile closeTheFile; catch(fileopenFailed) dosomething; catch(fileopenFailed) dosomething; catch(sizeDetermineFailed) dosomething; catch(sizeDetermineFailed)
6、 dosomething; catch(memoryAllocateFailed) dosomething; catch(memoryAllocateFailed) dosomething; catch(readFailed) dosomething; catch(readFailed) dosomething; catch(fileCloseFailed) dosomething; catch(fileCloseFailed) dosomething; 74.1 异常的概念异常的概念n和传统的方法比较异常的优点和传统的方法比较异常的优点:1.把错误代码从常规代码中分离出来把错误代码从常规代码
7、中分离出来2. 把错误传播给调把错误传播给调 用堆栈用堆栈3. 按错误类型和按错误类型和 错误差别分组错误差别分组4. 系统提供了对于一些无法预测的错误的系统提供了对于一些无法预测的错误的捕获和处理捕获和处理5. 克服了传统方法的错误信息有限的问题克服了传统方法的错误信息有限的问题method1method2method3method4产生异常传 递处理异常84.1 异常的概念异常的概念n.class ExcepTest public void main(String args) int b=0; int a; try a=4/b; catch(ArithmeticException e) S
8、ystem.out.println(“divided by 0”); try URL url=new URL(http:/ e) badURL=true; repaint();94.2 异常的分类异常的分类n异常是一个对象异常是一个对象,它继承自它继承自Throwable类类,所有的所有的Throwable类的子孙类所产生的对象都是例外类的子孙类所产生的对象都是例外.nError:由由Java虚拟机生成并抛出虚拟机生成并抛出,Java程序不做程序不做处理处理.nRuntime Exception(被被0除等系统错误除等系统错误,数组下数组下标超范围标超范围):由系统检测由系统检测, 用户的用户
9、的Java 程序可不做程序可不做处理处理,系统将它们交给缺省的异常处理程序系统将它们交给缺省的异常处理程序.nException(程序中的问题程序中的问题,可预知的可预知的): Java编译编译器要求器要求Java程序必须捕获或声明所有的非运行程序必须捕获或声明所有的非运行时异常时异常nthrow:用户自己产生异常用户自己产生异常104.2 异常的分类异常的分类n.ThrowableErrorExceptionExceptionRuntimeException缺省的异常缺省的异常处理程序处理程序由用户捕获或由用户捕获或声明并处理声明并处理不做处理不做处理用户自己产生的异常用户自己产生的异常要处
10、理要处理114.3 捕获异常捕获异常n捕获并处理异常捕获并处理异常try try / /接受监视的程序块接受监视的程序块, ,在此区域内发生在此区域内发生 /的异常的异常, ,由由catchcatch中指定的程序处理中指定的程序处理; ; catchcatch( (要处理的异常种类和标识符要处理的异常种类和标识符) ) / /处理异常处理异常; ; catchcatch( (要处理的异常种类和标识符要处理的异常种类和标识符) ) / /处理异常处理异常; ; 124.3 捕获异常捕获异常n常见的异常常见的异常nArithmeticExceptionArithmeticExceptionnArr
11、ayIndexOutOfBandsExceptionArrayIndexOutOfBandsExceptionnArrayStoreExceptionArrayStoreExceptionnIOExceptionIOExceptionnFileNotFoundExceptionFileNotFoundExceptionnNullPointerExceptionNullPointerExceptionnMalformedURLExceptionMalformedURLExceptionnNumberFormatExceptionNumberFormatExceptionnOutOfMemoryE
12、xceptionOutOfMemoryException如果在使用能够如果在使用能够产生异常的方法产生异常的方法而没有捕获和处而没有捕获和处理,将不能通过理,将不能通过编译编译134.3 捕获异常捕获异常n例例:编写编写Java程序程序,包含三种异常包含三种异常n算术异常算术异常, 字符串越界字符串越界,数组越界数组越界n观察输出信息观察输出信息:n每个异常对象可以直接给出信息每个异常对象可以直接给出信息144.3 捕获异常捕获异常class first_exception public static void main(String args) char c; int a,b=0;int a
13、rray=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);154.3 捕获异常捕获异常l一定会
14、执行的程序块一定会执行的程序块-finally-finally异常处理的统一出口异常处理的统一出口try try / /常规的代码常规的代码; ; catch()catch() / /处理异常处理异常 finally finally / /不论发生什么异常不论发生什么异常( (或者不发生任何异或者不发生任何异常常),),都要执行的部分都要执行的部分; ; 164.3 捕获异常捕获异常nfinally在文件处理时非常有用在文件处理时非常有用ntry n 对文件进行处理的程序对文件进行处理的程序;ncatch(IOException e) n /对文件异常进行处理对文件异常进行处理;nfinall
15、y n 不论是否发生异常不论是否发生异常,都关闭文件都关闭文件;n174.4 声明异常声明异常n一个方法不处理它产生的异常一个方法不处理它产生的异常, ,而是沿着调用层次而是沿着调用层次向上传递向上传递, ,由调用它的方法来处理这些异常由调用它的方法来处理这些异常, ,叫声叫声明异常明异常. .l声明异常的方法声明异常的方法l在产生异常的方法名后面加上要抛出在产生异常的方法名后面加上要抛出(throws)(throws)的的异常的列表异常的列表nvoid compute(int x)throws void compute(int x)throws ArithmeticException Ari
16、thmeticException nreturnType methodName(parameterlist) returnType methodName(parameterlist) throwsthrows exceptionList exceptionList184.4 声明异常声明异常例例:若因若因某种原某种原因不想因不想在创建在创建URL的的方法中方法中处理异处理异常常public method1() int x; try x=System.in.read(); compute(x); catch(IOException ioe) System.out.println(“read er
17、ror”); catch(ArithmeticException e) System.out.println(“devided by 0”); public int compute(int x) throws ArithmeticException e) return z=100/x;194.4 声明异常声明异常method1computer异常异常抛出抛出处理处理204.4 声明异常声明异常例例:说出程序执行结果说出程序执行结果public class exception1 void Proc(int sel) throws ArithmeticException, ArrayIndexOu
18、tOfBoundsException 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; 214.4 声明异常声明异常public static void main(String args) try Proc(0); Proc(1); catch(ArrayIndexOutOfBoundsException e) System.out.println
19、(Catch+e); c:jview throwsExceptionc:jview throwsExceptionIn Situation 0In Situation 0no Exception caughtno Exception caughtIn Situation 1In Situation 1Catch Catch java.lang.ArrayIndexOutOfBoundsException:10java.lang.ArrayIndexOutOfBoundsException:10224.5 抛出异常抛出异常l抛弃异常抛弃异常: 不是出错产生不是出错产生,而是人为地抛出而是人为地抛
20、出nthrow ThrowableObject;nthrow new ArithmeticException();n例例:编写程序人为抛出编写程序人为抛出(JavaThrow.prj) ArithmeticException, ArrayIndexOutOfBoundsException StringIndexOutOfBoundsExceptionA methodExceptionAnother methodthrowcaught234.5 抛出异常抛出异常class JavaThrow public static void main(String args)try throw new Ar
21、ithmeticException();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);
22、244.6 创造自己的异常创造自己的异常n不是由不是由Java系统监测到的异常系统监测到的异常(下标越界下标越界,被被0-除等除等),而是由用户自己定义的异常而是由用户自己定义的异常.n用户定义的异常同样要用用户定义的异常同样要用try-catch捕获捕获,但但必须由用户自己抛出必须由用户自己抛出 throw new MyException.n异常是一个类异常是一个类,用户定义的异常必须继承自用户定义的异常必须继承自Throwable或或Exception类类,建议用建议用Exception类类.254.6 创造自己的异常创造自己的异常n形如形如:nclass MyException exte
23、nds Exceptionn.; n例例1 :计算两个数之和计算两个数之和,当任意一个数超出范围时当任意一个数超出范围时,抛出自己的异常抛出自己的异常public class NumberRangeException extends Exception public NumberRangeException(String msg) super(msg); 264.6 创造自己的异常创造自己的异常n. public boolean action(Event evt, Object arg) try int answer = CalcAnswer(); answerStr = String.val
24、ueOf(answer); catch (NumberRangeException e) answerStr = e.getMessage(); repaint(); return true; 274.6 创造自己的异常创造自己的异常n.public int CalcAnswer() throws NumberRangeException int int1, int2; int answer = -1; String str1 = textField1.getText(); String str2 = textField2.getText(); try int1 = Integer.parse
25、Int(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;284.6 创造自己的异常创造自己的异常n例例2 :在定义银行类时在定义
26、银行类时,若取钱数大于余额若取钱数大于余额则作为异常处理则作为异常处理(InsufficientFundsException).n思路思路:产生异常的条件是余额少于取额产生异常的条件是余额少于取额, 因因此是否抛出异常要判断条件此是否抛出异常要判断条件n取钱是取钱是withdrawal方法中定义的动作方法中定义的动作,因因此在该方法中产生异常此在该方法中产生异常.n处理异常安排在调用处理异常安排在调用withdrawal的时候的时候,因此因此withdrawal方法要声明异常方法要声明异常,由上级由上级方法调用方法调用n要定义好自己的异常类要定义好自己的异常类294.6 创造自己的异常创造自己
27、的异常n.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() Sy
28、stem.out.println(The balance is +(int)balance);304.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(); 314.6 创造自己的异常创造自己的异常n.pub
29、lic 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; 324.7 小结小结1.1.一般格式一般格式: :正常程序和出错处理分离开来正常程序和出错处理分离开来try Java statement;catche(ExceptionType1 ExceptionObject) Exception1 handling; catche(ExceptionType2 E
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 酱香酒代理知识培训课件
- 癸卯兔年工作总结与新年展望
- 2025年春幼儿园教学工作方案
- 2025年班主任工作方案目标
- 酒的专业知识培训课件
- 2025年工作方案怎么写参考演讲稿
- 2025年教育工作方案总结
- 少儿创意美术课程介绍
- 班级管理学年报告
- 提供人情味的服务
- 工程项目代建管理
- 华南理工大学自主招生个人陈述自荐信范文
- DB21T 3806-2023 电梯检验检测全程录像工作规范
- 10.3常见的盐(第1课时)教学设计-2024-2025学年九年级化学人教版(2024)下册
- 2024年社区警务规范考试题库
- 保安保洁服务方案
- 汽车修理业务受理程序、服务承诺、用户抱怨制度
- 起重机械吊具、索具检查记录表(钢丝绳)
- 小学三年级毛笔书法教案含三维目标
- 土木工程毕业论文7篇
- 代加工洗煤合同模板
评论
0/150
提交评论