ch8_Exception Handling_异常处理ppt课件.ppt

上传人:春哥&#****71; 文档编号:16978131 上传时间:2022-05-20 格式:PPT 页数:68 大小:918.50KB
返回 下载 相关 举报
ch8_Exception Handling_异常处理ppt课件.ppt_第1页
第1页 / 共68页
ch8_Exception Handling_异常处理ppt课件.ppt_第2页
第2页 / 共68页
点击查看更多>>
资源描述

《ch8_Exception Handling_异常处理ppt课件.ppt》由会员分享,可在线阅读,更多相关《ch8_Exception Handling_异常处理ppt课件.ppt(68页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、ch8_Exception Handling_异常处理Chapter 8 Exception Handling异常处理异常处理8.1 Concepts The ideal time to catch an error is at the source programs compile time, before you even try to run it. However, not all errors can be detected at the compile time. The rest problems must be handled at run time through some

2、formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the errors properly. When a program runs into a runtime error, how can you handle the runtime error so that the program can continue to run or terminate gracefully? This is th

3、e subject we will introduce in this chapter. Error discovery is a fundamental concern for every program you write. The goals for exception handling in Java are to simplify the creation of large, reliable programs using less code and try to make your application doesnt have an unhandled error. Becaus

4、e exception handling is the only official way that Java reports errors, and it is enforced by the Java compiler.8.1 Concepts 异常处理的概念 能够在执行程序前,在编译时发现错误时最理想的。然而,不是所有错误都能够在编译阶段发现。有些错误只能在程序运行时发现并处理。如果出现错误,需要将错误信息发送给程序的使用者,让其做出正确的处理。 当程序出现运行时运行时错误,怎样做出处理,才能让程序继续运行或者恰当地结束呢?这是本章的主题。能够发现运行时运行时错误错误是对程序代码的基本要

5、求。 Java异常处理机制能够简化大规模、可靠性高的程序的设计。必须使应用程序能够处理所有的错误。Java异常处理的基本方式是报告错误报告错误,指出错误发生的原因。Java编译器强制程序对编译器强制程序对某些某些可能的异常进行处理。可能的异常进行处理。 Java handles the exception in one place, in the so-called exception handler. Exception handling separates error-handling code from normal programming tasks, thus making prog

6、rams easier to read and to modify. If an error happens, the exception-handling mechanism takes over and begins to look for an appropriate place to continue executing the program. Java 在专门的代码段在专门的代码段,所谓的“异常处理器”处理异常。异常处理代码与程序正常执行的代码分离,使程序易阅读,易修改。 如果发生错误,异常处理机制(异常处理器)对问题进行处理,设法让程序继续执行。 try 可能出现问题的代码cat

7、ch (异常类型) 异常处理代码(异常处理器)异常处理代码(异常处理器) 8.2 Exception classes 异常类ObjectThrowableExceptionError Two kinds of exceptionsProgram deals with or throwJVM deals with and throw Java provides an exception dealing mechanism (classes) to help dealing with runtime exceptions. Java 采用一个异常处理机制(通过提供异常类异常类)帮助我们处理运行时运

8、行时异常。ObjectThrowableExceptionErrorRuntimeExceptionNon_RuntimeException运行时运行时错误举例package kkk;public class ArrayError public static void main(String args) char ch=你,们,好,!; for(int i=0; i=ch.length; i+) System.out.print(chi); /line 6 System.out.println(这条语句没有执行!这条语句没有执行!); 你们好你们好!Exception in threadmai

9、njava.lang.ArrayIndexOutOfBoundsException: 4at kkk.ArrayError.main(ArrayError.java:6)你们好!Exception in threadmain: 4 at kkk.ArrayError.main(ArrayError.java:6)下标是0,1,2,3,不该为4。Exception classesException class Hierarchy System errors are thrown by JVM. Such errors rarely occur. If one does, there is lit

10、tle we can do.Exception describes errors caused by the program and external circumstances. These errors can be caught and handled by the program.这些异常能够由程序捕捉并处理程序捕捉并处理。系统错误由JVM捕捉,程序没办法处理程序没办法处理。8.2.1 Runtime Exception Runtime Exception is caused by program logical errors that should be corrected in t

11、he program, such as bad casting, accessing an out-of-bounds array, and numeric errors. (“It is your fault”) Exceptions of RuntimeException, Error and their subclasses are Un-Recoverable Exceptions,for eample divides 0. RuntimeException 由程序的由程序的逻辑错误逻辑错误导致,例导致,例如数组越界,除数为如数组越界,除数为0等,应该等,应该由程序处理由程序处理。Ru

12、ntimeException, Error 以及它们的子类是不可恢复的异常不可恢复的异常,例如除数是 0。8.2.2 “Non-runtime” Exceptions Other exceptions are non-runtime exceptions, and are Recoverable. The compiler forces the programmer to check and deal with the exceptions. Such us IOException.Bad thing(I/O error,)8.2.2 “Non-runtime” Exceptions 除了Ru

13、ntimeExceptions,其余叫做“非运行时异常”,是可可恢复的异常恢复的异常,例如输入非法,可以重新输入,文件坏了,修复后可以正常访问。编译器强制程序处理该类异常编译器强制程序处理该类异常。例如IOException,如果不处理,程序不能通过编译。Common runtime exception classes ArithmeticException 算数异常ArrayIndexOutOfBoundsException 数组越界NullPointerException。 空引用IncompatibleClassChangeException NoClassDefException In

14、compatibleTypeException Each exception class represents a kind of running error. The class deals with the specific error and reports the error information. When an error does happen, an instance of that exception class is created and the error is dealt to avoid dead cycling run and any damages to th

15、e operating system. 每个异常类代表一种每个异常类代表一种运行时运行时错误错误。对应的类处理特定的错误并报告错误信息。当出现错误时,系统自动创建一个该类的实例自动创建一个该类的实例,并对该错误进行处理对该错误进行处理,防止死循环或者对操作系统的任何危害。 8.3 Ways of Exception dealing 异常处理方式 When an exception happens, Java JVM creates an instance automatically with relative subclass of Exception and wait to be dealt

16、 with. This is called throw an exception, or thrown an instance) For example, while try to read an un-existed file, the IOException class will create an instance (throw the exception) , and wait to be dealt with. So the task of the exception dealing is to catch the exceptions and deal with them. Sys

17、tem throw an exception automaticallyAll RuntimeExceptions are thrown automaticallyAll Error are thrown automatically 8.3 Ways of Exception dealing 异常处理方式 发生异常时,Java JVM 自动创建一个对应的异常实例,并等自动创建一个对应的异常实例,并等待处理。待处理。这就是抛出异常这就是抛出异常。 例如试图读一个不存在的文件时,JVM会自动创建一个IOException 类的实例(即抛出异常),并等待被处理。因此程序程序进行异常处理的任务是捕捉到

18、这个被抛出的异常进行异常处理的任务是捕捉到这个被抛出的异常,并进行处理。系统会自动抛出异常抛出异常RuntimeExceptions 会被自动抛出Error 会被自动抛出 There are two types of exception dealing ways: 1) catch and handling 2) throw it The exception will guarantee that someone catches it. If the program refuses to catch or to throw an exception, JVM would deal it, st

19、op running and report the exception information. Throw the exception: Create an instance and report (display) the exception information (the type, the position). 有2种方式处理异常: 1) 捕捉并处理捕捉并处理 2) 抛出异常(抛出异常(给方法的调用者给方法的调用者)。 异常一定会被抛出异常一定会被抛出。如果程序不处理,JVM会处理,在异常处中断程序,并报告异常信息。 抛出异常抛出异常:创建对应的异常实例创建对应的异常实例,报告异常信

20、息。报告异常信息。Two types of exception dealing ways 2种异常处理的方式Example of throw an exception At run time, if an exception happened, Java JVM will automatically throw the exception. However this kind of information is terrible for the software users. A good program deals the exception within the program. Exce

21、ption is thrown (an instance is thrown). If fail to deal with, the program interrupts at the exception point.How to recover from this ? (no way)JVM displays predefined error information.Exception in thread main : 4 at kkk.ArrayError.main(ArrayError.java:6)Example of an exceptionExample of 2 command

22、line parameters.public class Tradition public static void main(String args) System.out.println(“The parameters are:” +args0+”,”+args1); Runtime exception An exception is an error throw, which reports error information. 异常是抛出错误(创建对象、处理、报告错误信息)When JVM or you throw an exception:1) An exception instanc

23、e is created in the same way that any Java instance is created, on the heap, with new. 2) The current path of execution (the one you couldnt continue) is stopped . At this point the exception-handling mechanism takes over and begins to look for an appropriate place to continue executing the program.

24、 无论是JVM还是我们都可以抛出异常,抛出异常抛出异常,会做下面2件事:创建创建 exception 实例实例(与创建其它Java实例的方式相同,在堆中,用new) 不再沿当前的路径执行程序。终止当前程序的执行路径终止当前程序的执行路径 异常处理机制接手进行处理,并设法从其它地方继续程序的执异常处理机制接手进行处理,并设法从其它地方继续程序的执行。行。 Throw an exception 8.4 Catch and dealing exceptions 捕捉与处理异常Traditional way of exception dealing. 传统的异常处理方法传统的异常处理方法,还可用还可用

25、public class Tradition public static void main(String args) if(args.length2) System.out.println(命令行必须有命令行必须有 2 个参数个参数!); else System.out.println( 2 个参数是个参数是:+args0+,+args1); /Acceptable to the users. You can use it.Use Exception Dealing Scheme 异常处理机制trycatch /catch and dealing public class JavaWay p

26、ublic static void main(String args) try System.out.println(The parameters are:+args0+,+args1); catch(ArrayIndexOutOfBoundsException a) System.out.println(Command must include 2 parameters!); System.out.println(Program continue!); Exception handling separates error-handling code from normal programmi

27、ng tasks, thus making programs easier to read and to modify.report errors to the callerCommand must include 2 parameters!Program continue!JVM throws the error (create an instance and assign it to a)JVM 抛出的异常被捕捉到,异常实例被赋值给抛出的异常被捕捉到,异常实例被赋值给 apublic class JavaWay public static void main(String args) tr

28、y System.out.println(The params are:+args0+,+args1); catch(ArrayIndexOutOfBoundsException a) System.out.println(must include 2 params! +a); /System.out.println(must include 2 params! +a.toString(); /System.out.println(Program continue!); Command must include 2 parameters!: 0Program continue!Number o

29、f parameters 0a is the ArrayIndexOutOfBoundsException type reference, and is assigned with an instance of the ArrayIndexOutOfBoundsException type. trycatchfinally When an exception happens, Java JVM creates an instance automatically with relative subclass of Exception (thrown an exception, or thrown

30、 an instance) and wait to be dealt with. 遇到异常,JVM抛出异常,等待处理。trycatchtry statements; / Statements may throw exceptions /as long as an exception is detected, stop and jump to a catch block. /if none of exception is throw, finish the statements in the blockcatch(Exception1 e1) handler for exception1; /h

31、andling an exceptioncatch(Exception2 e2) /handling an exception handler for exception2;.catch(ExceptionN eN) /any number of catch blocks, at most, only handler for exceptionN; /one can be executedIf an exception is detected, JVM wont display the predefined information if one of the catch blocks is e

32、xecuted.Exceptions are caught by their typestrycatchtry 语句; / 可能引起异常的语句可能引起异常的语句(可能抛出异常的语句) /只要检测到异常只要检测到异常,立即停止执行并进入某个立即停止执行并进入某个catch块块。 /如果未发生异常,完成本块中语句的执行如果未发生异常,完成本块中语句的执行。catch(Exception1 e1) handler for exception1; /处理异常器catch(Exception2 e2) /处理异常 handler for exception2;.catch(ExceptionN eN)

33、/任意数目的任意数目的 catch块,至多只有一个被执行块,至多只有一个被执行 handler for exceptionN; 如果检测到异常,如果检测到异常,如果某个catch块被执行,JVM不会显示设定的信息。按类型捕捉异常按类型捕捉异常finally子句Try statements;catch(TheException ex) handling ex; finally finalStatements;/一定被执行一定被执行E.g. try int x, y = 5, z = 0; x = y/z; int myArray=new int20; myArray20 = 1000;catch

34、(ArithmeticException ae) System.out.println(Dealing 0.);catch(ArrayIndexOutOfBoundsException et1) System.out.println(Dealing over bounds.);finally System.out.println(must execute.);Dealing 0.must execute.E.g. try int x, y = 5, z = 0; /x = y/z; int myArray=new int20; myArray20 = 1000;catch(Arithmetic

35、Exception ae) System.out.println(Dealing 0.);catch(ArrayIndexOutOfBoundsException et1) System.out.println(Dealing over bounds.);finally System.out.println(must execute.);Dealing over bounds.must execute.E.g. try int x, y = 5, z = 0; x = y/z; int myArray=new int20; myArray20 = 1000;catch(ArrayIndexOu

36、tOfBoundsException et1) System.out.println(Dealing over bounds.);finally System.out.println(must execute.);must execute.Exception in thread main : / by zeroat kkk.ArrayError.main(ArrayError.java:6)Exampletry statementscatch(Exception ae) statementscatch(ArrayIndexOutOfBoundsException et1) statements

37、finally statementsCatch clauses are checked in order The parent exception should be caught at the last catch block. A compile error occurs if the super-type is arranged before the sub-type. Never be executed./statementstry / statements try / statements catch(ExceptionType1 ae) / statements catch(Exc

38、eptionType2 et1) /statements finally / statements / statementscatch(ExceptionType3 e) / statements Embedded Exception When error occurs, a method can throw an exception, which provides the method an alternative exit path. But, the code calling the method should catch and handle the thrown exceptions

39、. 发生错误时,方法可以抛出异常方法可以抛出异常,这给了方法另外一个退出的途径。但调用调用这个抛出了异常的方法要捕捉与处理异常的方法要捕捉与处理异常。8.5 Throwing Exceptions 抛出异常8.5.1 throw JVM detects and throws Exceptions, the program can throw Exceptions too. When the program detects an error, the program can create an instance of an appropriate exception type and throw

40、 it to another method or JVM. This is known as throwing an exception. If a method encounters a situation it cant or doesnt like to manage, it can throw an exception and let the calling method deal with it. JVM 能够检测并抛出异常,程序代码也可以这样做。检测到错误时,如果方法无法处理,或者不愿意处理如果方法无法处理,或者不愿意处理,也可以像JVM那样,抛出异常,即创建相关类型的实例即创建相

41、关类型的实例, 然后抛出,抛给其它方法,让调用它的方法处理让调用它的方法处理或者抛给JVM。/create an instance of The Exception and then throw itTheException ex=new TheException();/create exception instancethrow ex; /throw instanceOrthrow new TheException(); /throw instanceOrthrow new TheException(String of information); The information is an

42、option, which is added to the return String of the toString method.In a method, statements after throw ex; wont be executed. The system starts to search try blocks one by one.Example/创建异常实例,并抛出TheException ex=new TheException();/create exception instancethrow ex; /throw instanceOrthrow new TheExcept

43、ion(); /throw instanceOrthrow new TheException(String of information); The information is an option, which is added to the return String of the toString method.方法里throw ex;后面的语句不再被执行,系统开始寻找 trycatch块。Example8.5.2 Throw basic exceptions(RuntimeException) 抛出基本类型的异常 Consider an reference called t. Its

44、possible hasnt been initialized, so you might want to check before trying to call a method using that object reference. You can send information about the error into a larger context by creating an instance representing your information and throwing it out of your current context. This is called thr

45、owing an exception. Heres what it looks like: if(t=null) throw new NullPointerException(); This allows youin the current codesto abdicate responsibility for thinking about the issue further.8.5.2 抛出基本类型的异常 假设有个引用 t,可能没被初始化就使用。使用前进行检查。如果发现问题,创建一个代表空引用的实例,将信息发送到其它方法,由其它方法处理。这叫抛出异常抛出异常。 if(t=null) thro

46、w new NullPointerException(); Or if(t=null) throw new NullPointerException(t = null); 含有这段代码的方法结束执行。含有这段代码的方法结束执行。More information One of the most important aspects of exceptions is that if something bad happens, they dont allow a program to continue along its ordinary path. Exceptions allow you to

47、(if nothing else) force the program to stop and tell you what went wrong, or (ideally) force the program to deal with the problem and return to a stable state. 重点是一旦发现异常,程序就不能按照原来的执行路径执行。异常处理机制迫使方法或者程序停止执行,报告错误信息,处理问题并回到正常状态。 8.5.3 Exception arguments 异常信息 While throwing an exception, an instance is

48、 created with new, a constructor is called. There are 2 constructors in all standard exceptions: public Exception(); / default constructor public Exception(String s); /constructor with a String argumentThe second takes a string argument so that you can place pertinent information in the exception: t

49、hrow new NullPointerException(t = null); This string can later be extracted using various methods. The keyword throw produces a number of interesting results. After creating an exception instance with new, you give the resulting reference to throw. The information about the error is represented both

50、 inside the exception instance and implicitly in the name of the exception class. 8.5.3 Exception arguments 异常信息 抛出异常时,用new创建异常实例, 会调用异常类的构造方法(包括其base类Exception的构造方法)。Exception类有2个构造方法,它们的原型是: public Exception(); / default constructor public Exception(String s); /constructor with a String argument 第

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁