第06章-异常处理_第1页
第06章-异常处理_第2页
第06章-异常处理_第3页
第06章-异常处理_第4页
第06章-异常处理_第5页
已阅读5页,还剩30页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、1面向对象程序设计(Java)异常的基本概念n异常(Exception)是程序执行过程中出现的非正常事件,即各种意外情况。比如说:n 用户输入出错n 所需文件找不到n 运行时磁盘空间不够n 内存不够2n 算术运算错 (数的溢出,被零除)n 数组下标越界n n 当Java程序出现以上的错误时,就会在所处的方法中产生一个异常对象。这个异常对象包括错误的类型,错误出现时程序的运行状态以及对该错误的详细描述。下面我们先看一个简单的例子。3npublic class ExceptionDemo n public static void main(String args) n int x=100;n Sy

2、stem.out.println(The result is+x/10);n System.out.println(Divided by zero: +x/0); 4n当我们对其编译后运行时,其对应的结果如下:nc:jbuilder3javabinjava Exception DemonThe result is10nException in thread main java.lang.Arithmetic Exception: / by zero at Exception Demo.main(Exception Demo.java:5)n 其意思是说,本程序执行到语句“System.out.

3、println (Divided by zero: +x/0)”时,系统会抛出一个例外,该例外在Java中定义为Arithmetic Exception (即属于算术运算例外)。5异常的处理机制n我们知道,一旦程序在执行的过程中出现异常,往往有两种处理方式:n (1) 当程序出现错误的时候,系统将终止程序的运行,如例5.1。在Java中这是属于运行异常,用户不加干预,完全交由系统对其进行处理。6n(2) 当程序出现错误时,采用捕捉抛出(catch-throw)的面向对象编程方式。该种方式是当程序运行出错时,系统和程序抛出各种标准类型的错误,程序捕捉该错误并进行相应处理。由于异常均以标准的形式提

4、供,使得程序员能以统一的方式对异常进行处理。n 通常,Java的出错与异常处理采用“try, catch, throws”语句来实现,下面我们分别加以介绍。781.异常和异常类2.异常处理3.创建异常第六章 异常处理9n软件程序肯定会发生错误/问题nwhat really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die? n从外部问题(硬盘、网络故障等)到编程错误(数组越

5、界、引用空对象等)n致命错误n内存空间不足等错误(Error)导致程序异常中断n程序不能简单地恢复执行n非致命错误n数组越界等异常(Exception)导致程序中断执行n程序在修正后可恢复执行异常(Exception)10nJava语言中已定义或用户定义的某个异常类的对象n一个异常类代表一种异常事件nJava语言利用异常来使程序获得处理错误的能力(error-handling) n异常事件(Exceptional Event)nAn exception is an event that occurs during the execution of a program that disrupts

6、 the normal flow of instructions. 异常异常类的类层次nJava语言采用继承的方式组织各种异常,所有的异常类都直接或间接地继承于类Throwable。我们可用图5.1描述异常的常用类层次。n 从图5.1中可以看出,Throwable类是所有异常类的父类。它分为两个子类:Error类和Exception类。Error类包括动态链接失败、虚拟机出错等异常,该类异常Java不要求捕获,同时系统也不会抛出该类异常1112ThrowableErrorExceptionLinkageErrorVirtualMachineErrorAWTErrorAWTExceptionIO

7、ExceptionRuntimeExceptionArithmeticExceptionInterruptedExceptionIndexOutOfBoundsExceptionFileNotFoundExceptionEOFException13nJava语言中用来处理异常的类n异常类的方法n构造方法npublic Exception()npublic Exception(String s)n常用方法npublic String toString()npublic String getMessage()npublic void printStackTrace()异常类14n对异常的定义nJa

8、va语言中定义的异常类: IOException/NullPointerExceptionn详细定义见Java文档中各个包的Exception Summaryn用户定义自已所需的异常类,描述程序中出现的异常结果第10讲 异常(Exception)class java.lang.Throwable class java.lang.Error (严重的问题,但不需程序捕捉的错误) class java.lang.LinkageError . . class java.lang.VirtualMachineError class java.lang.InternalError class java.

9、lang.OutOfMemoryError . . class java.lang.Exception(程序应该捕捉的错误) class java.lang.ClassNotFoundException class java.lang.RuntimeException (JVM正常运行时抛出的错误) class java.lang.ArithmeticException . . class java.io.IOException class java.awt.AWTException class java.sql.SQLException . .151.异常和异常类2.异常处理3.创建异常第六

10、章 异常处理16n当一个Java程序的方法产生一个错误,该方法创造一个异常对象并将其交给运行系统nIn Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception(抛出异常)n运行系统从错误发生处开始寻找处理错误的程序段nThe exception handler chosen is said to catch the exception(捕获异常)n捕获异常的过程可以沿方法调用的逆向顺序寻找异常处理17n异常处理器(exc

11、eption handler)ntryncatchnfinallyn异常的抛出(throw)异常处理18n何时会出现异常?n方法中已定义了异常的抛出异常处理import java.io.IOException;class jex3_3 public static void main(String args) throws IOException char c;System.out.println(Please input a char: );c = (char)System.in.read();System.out.println(Received char= + c);public abst

12、ract int read() throws IOException在程序编译的时候必须完成异常的处理19n由于非预期的结果导致系统运行时产生异常异常处理class jex7_9 public static void main(String args) int a = 0;int b = 24/a;java jex7_9Exception in thread main“java.lang.ArithmeticException: / by zeroclass jex7_9 public static void main(String args) int i = Integer.parseInt

13、(args0);System.out.println(i);java jex7_9Exception in thread main“java.lang.ArrayIndexOutOfBoundsException: 0java jex7_9 aException in thread main“java.lang.NumberFormatException: For input string: “a”20n异常处理器(exception handler)ntryncatchnfinally异常处理21n异常处理器(exception handler)ntry程序块 n构造一个异常处理器,封装一些

14、抛出异常的语句try Java 语句块; /指一个或多个抛出异常的Java语句异常(Exception)class Test public static void main(String args) char c = (char)System.in.read(); System.out.println(c); import java.io.IOException;class Test public static void main(String args) try char c = (char)System.in.read(); System.out.println(c); catch (IO

15、Exception e) System.out.println(e); unreported exception java.io.IOException;must be caught or declared to be thrownchar c = (char)System.in.read();一个try语句必须带有至少一个catch语句块或一个finally语句块22n异常处理器(exception handler)ntry语句块定义了异常处理器的范围ncatch语句块捕捉try语句块抛出的异常try / Code that might generate exceptions catch(T

16、ype1 id1) / Handle exceptions of Type1 catch(Type2 id2) / Handle exceptions of Type2 catch(Type3 id3) / Handle exceptions of Type3/ etc .异常处理import java.io.IOException;class Test public static void main(String args) try char c = (char)System.in.read(); System.out.println(c); catch (IOException e) Sy

17、stem.out.println(e); try . . . catch (ArrayIndexOutOfBoundsException e) System.out.println(e); catch (IOException e) System.out.println(e);23n异常处理器(exception handler)nfinally语句块nTheres often some piece of code that you want to execute whether or not an exception is thrown within a try block.nfinally

18、语句块在异常处理中是必须执行的语句块n清理现场n关闭打开的文件n关闭网络连接异常处理try / The guarded region: Dangerous activities / that might throw A, B, or C catch(A a1) / Handler for situation A catch(B b1) / Handler for situation B catch(C c1) / Handler for situation C finally / Activities that happen every time24n异常的抛出n在一个方法中,抛出异常,同时捕

19、捉n当有多个方法调用时,由特定(适当)的方法捕捉异常n被调用的方法主动抛出异常(throws)异常处理import java.io.IOException;class Test static char getChar() throws IOException char c = (char)System.in.read(); return c; public static void main(String args) try char c = getChar(); System.out.println(c); catch (IOException e) System.out.println(e)

20、; 25n异常的抛出n主动抛出异常异常处理 void parseObj(String s) throws NullPointerException if (s = null) throw new NullPointerException(); ; 261.异常和异常类2.异常处理3.创建异常第六章 异常处理27n使用Java语言已有的异常异常的抛出/捕捉n创建自已的异常异常的抛出/捕捉创建异常28异常(Exception)class SimpleException extends Exception public class SimpleExceptionDemo public void f(

21、) throws SimpleException System.out.println(Throw SimpleException from f(); throw new SimpleException(); public static void main(String args) SimpleExceptionDemo sed = new SimpleExceptionDemo(); try sed.f(); catch(SimpleException e) System.out.println(e); System.out.println(Caught it!); 运行结果:Throw S

22、impleException from f()SimpleExceptionCaught it!29n自定义异常n自定义异常类必须是java.lang.Exception类的子类njava.lang.Exception类的两个构造方法nExceptionException() Constructs a new exception with null as its detail message.nExceptionException(Stringmessage) Constructs a new exception with the specified detail message.n自定义异常

23、类可以不定义构造方法nSimpleException() super(); n自定义异常类定义自已的构造方法创建异常30n定义自已的异常构造方法创建异常31class MyException extends Exception private int x; public MyException() public MyException(String msg) super(msg); public MyException(String msg, int x) super(msg);this.x = x; class ExtraFeatures public static void f() thr

24、ows MyException System.out.println(Throws MyException from f(); throw new MyException(); public static void g() throws MyException System.out.println(Throws MyException from g(); throw new MyException(Originated in g(); public static void h() throws MyException System.out.println(Throws MyException

25、from h(); throw new MyException(Originated in h(), 47); try f(); catch(MyException e) System.out.println(e);Throwing MyException from f()MyExceptiontry g(); catch(MyException e) System.out.println(e);Throwing MyException from g()MyException: Originated in g()Throwing MyException from h()MyException:

26、 Originated in h()try h(); catch(MyException e) System.out.println(e);32nQuiznQuestion: Is the following code legal?异常(Exception)try . finally .nAnswer: Yes, its legal. A try statement does not have to have a catch statement if it has a finally statement. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally statement is executed no matter

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论