异常捕获和枚举类型.ppt_第1页
异常捕获和枚举类型.ppt_第2页
异常捕获和枚举类型.ppt_第3页
异常捕获和枚举类型.ppt_第4页
异常捕获和枚举类型.ppt_第5页
已阅读5页,还剩39页未读 继续免费阅读

下载本文档

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

文档简介

Chapter 15,异常处理 补充:枚举类型,2,语法错误,编译错误,逻辑错误,Syntax errors (语法错误)-编译过程中出现的错误,通过编译器检测。 Runtime errors (运行时错误)引起程序非正常中断的错误。 Logic errors (逻辑错误)指程序没有按期望的要求执行。,3,运行错误,如果这行出现异常,将跳过其余的行,程序终止。,4,捕获运行错误,5,异常类(Exception Classes),page 446,6,系统错误(System Errors),System errors 是由JAVA虚拟机抛出并在Error类中描述的。Error类描述内部的系统错误。这种错误很少发生,如果发生,除了通知用户以及尽量稳妥地结束程序外,几乎什么也不能做。,page 446,7,异常(Exceptions),Exceptions 是由Exception类描述的。 Exception类描述由程序和外部环境引起的错误,这些错误能通过程序捕获和处理。,page 446,8,Runtime Exceptions,Runtime exceptions 是由 RuntimeException 类描述编程错误,比如不合适的转换,访问一个越界数值或数值错误等。运行异常通常由JAVA虚拟机抛出。,page 446,9,必检异常和免检异常,RuntimeException, Error 以及它们的子类都称为免检异常(unchecked exceptions). 所有其他异常都称为必检异常(checked exceptions). unchecked exception 是程序设计中不可重获的逻辑错误。 checked exception 编译器强制程序员检查并处理异常,10,必检异常和免检异常,Unchecked Exceptions,Java 不能保证你的代码能够捕获或声明unchecked exceptions.,11,声明、抛出、捕获异常,catch exception,declare exception,throw exception,12,声明异常,声明异常(declaring exceptions)-每个方法都必须说明它可能抛出的必检异常的类型. 如: public void myMethod() throws IOException public void myMethod() throws IOException, OtherException ,13,抛出异常,抛出异常(throwing an exception)程序检测到一个错误后,创建一个适当类型异常的实例并抛出它。 这里有一个例子: throw new TheException(); TheException ex = new TheException(); throw ex;,14,抛出异常,/* Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException if (newRadius = 0) radius = newRadius; else throw new IllegalArgumentException( “Radius cannot be negative“); ,15,捕获异常 ,try statements; / Statements that may throw exceptions catch (Exception1 exVar1) handler for exception1; catch (Exception2 exVar2) handler for exception2; . catch (ExceptionN exVar3) handler for exceptionN; ,page 448,16,java.lang.Throwable 方法,public String getMessage() 返回Throwable对象的详细信息 public String toString() 返回3个字符串合起来的串,它们分别是:异常类名的全称; “:”一个冒号和一个空格; getMessage()方法。 public void printStackTrace() 在控制台上输出Throwable对象及其踪迹信息。,17,例15.1 声明、抛出和捕获异常 ,问题: 本例演示如何声明、抛出和捕获异常,改写6.10 节中setRadius 方法,如果半径是负的,新的 setRadius 方法抛出一个异常。,TestCircleWithException,CircleWithException,page 449,18,output java.lang.IllegalArgumentException: Radius cannot be negative Number of objects created: 1,System.out.println(ex); is equivalent to System.out.println(ex.toString();,例15.1(续) ,说明:在此例中,由于IllegalArgumentException是一个RuntimeException (unchecked Exception),所以在测试程序中若没有编写try-catch代码,编译时不会报错,只会在运行时抛出异常。(栈跟踪),19,输出 (no try-catch block) Exception in thread “main“ java.lang.IllegalArgumentException: Radius cannot be negative at CircleWithException.setRadius(CircleWithException.java:30) at CircleWithException.(CircleWithException.java:15) at TestCircleWithException.main(TestCircleWithException.java:5),例15.1(续),说明:若把程序中的try-catch都删除,就会显示以上的运行效果,从运行中可以看出异常栈的跟踪次序。 另外,若保留try-catch块,在代码中执行ex.printStackTrace()也可以显示异常栈。,20,捕获或声明异常,Java 强迫程序员处理必检异常 如果方法声明了一个必检异常,必须在try-catch 块中调用它或者在调用它方法中声明抛出异常。例如, 假设方法 p1 调用方法 p2 。方法 p2 将抛出一个异常 (e.g., IOException), 程序员必须按照(A) 和(B)编写程序.,(A),(B),21,Catching Exceptions,main method . try . invoke method1; statement1; catch (Exception1 ex1) Process ex1; statement2; ,method1 . try . invoke method2; statement3; catch (Exception2 ex2) Process ex2; statement4; ,method2 . try . invoke method3; statement5; catch (Exception3 ex3) Process ex3; statement6; ,An exception is thrown in method3,page 449,22,Note ,在catch子句中制定异常的顺序是非常重要的。,page 449,23,重新抛出异常,try statements; catch(TheException ex) perform operations before exits; throw ex; ,语句 throw ex 重新抛出异常,以便其他处理器获得处理异常ex的机会。,24,finally 子句,try statements; catch(TheException e) handling e; finally finalStatements; ,说明:无论之前的try和catch块中发生了什么,以下finally代码块中的代码都一定会执行: try代码块执行完成,没有发生异常; try代码块发生异常,被某个catch代码块处理; try代码块发生异常,没有被任何一个catch代码块处理。,Note: Catch blocks are unnecessary if a finally block is present: try finally ,25,如何使用异常,异常处理可以将错误处理代码从正常的编程任务分离出来,这样可以使程序变得容易阅读和修改,然而应该注意,由于异常处理需要初始化新的异常对象并重返调用堆栈,并且通过方法调用链传播异常以便搜寻异常处理器。,26,何时抛出异常,一个方法出现异常时,如果想让该方法的调用者处理异常,应该创建一个异常对象并对其抛出。如果能在发生 异常的方法中处理异常,那么就不需要抛出异常。,27,何时使用异常,在代码中,应该什么时候使用try-catch块?当必须处理不可预料的错误时应该使用。不要用try-catch块处理简单、可预料的情况。例如下述代码:,try System.out.println(refVar.toString(); catch (NullPointerException ex) System.out.println(“refVar is null“); ,28,何时使用异常,最好用以下代码代替,if (refVar != null) System.out.println(refVar.toString(); else System.out.println(“refVar is null“);,注意:不要用异常捕获来解决那些可以用if语句判断的简单错误。 ,29,创建异常类,要创建自定义异常类型,需要利用继承来扩展某个预定义Java异常类。通常是直接扩展通用的Exception类: public class MissingValueException extends Exception 最简单的自定义异常类: public class MissingValueException extends Exception ,选讲,30,自定义异常类,简单的自定义异常类: public class MissingValueException extends Exception /Constructor public MissingValueException(String message) super(message); Exception类包含了public Exception(String message)方法; Exception类包含了String getMessage()方法,用于将这个传入的message信息显示出来; 因此自定义的异常类可以调用super(message);方法初始化父类,并且此自定义类也自动继承了getMessage()方法,用于显示异常信息串。,31,程序举例,public class MissingValueException extends Exception private Student student; public MissingValueException(Student s, String message) super(message); student = s; public Student getStudent() return student; ,定义异常类,此类存储在 MissingValueException.java文件中。,32,程序举例,public class Student private String name; private String ssn; public String getSsn() . public void setSsn() . public String getName() . public void setName(String n) throws MissingValueException if (n.equals(“) throw new MissingValueException(this, “A students name cannot be blank“); else name = n; / etc. ,使异常类在Student类中运作。,33,程序举例,public class Example public static void main(String args) String name = read value from GUI; Student s = new Student(); s.setName(name); / etc.,在试图调用setName方法的那行代码上将产生编译错误: Unreported exception MissingValueException; must be caught or declared to be thrown s.setName(name); 因为在Student类的setName方法声明中包含了throws MissingValueException子句,java编译器强制客户代码捕获这个类型的异常。,伪代码,34,程序举例,public class Example public static void main(String args) String name = read value from GUI; Student s = new Student(); try s.setName(name); catch (MissingValueException e) System.out.println(e.getMessage(); System.out.println(“ID of affected student: “ + e.getStudent().getSsn(); / etc.,输出结果: A students name cannot be blank ID of affected student: 123-45-6789,伪代码,补充: 枚举类型,36,枚举类型,将变量的取值约束到一个有限的集合。 例如:只希望学位的取值为: Mathematics Biology Chemistry Computer Science Physical Education 为保证客户代码不会传入一个不正确的专业值,因此创造一个自定义异常类型InvalidMajorExcetion,代码如下所示:,JDK 1.5 特征,37,public class Student private String name; private String major; public Student(String name, String major) throws InvalidMajorException this.setName(name); if (major not one of the five approved majors) throw new InvalidMajorException(); else this.setMajor(major); / 在运行时,若传入错误的参数,则会丢出异常 try Student s = new Student(“Dorothy Jost“, “Culinary Arts“); catch (InvalidMajorException e) . ,此例的缺点在于:只有在运行时异常才能发生,不能防止客户代码在编译时进行错误检测。,38,枚举类型的定义,public enum Major / Define name/value pairs Math(“Mathematics“), Bio(“Biology“), Chem(“Chemistry“), CS(“Computer Science“), PhysEd(“Physical Education“); /Declare the value attribute to be of type String. private final String value; / The constructor takes a String argument. Major(String v) value = v; / The method has a return type of String. public String value() return value; ,39,枚举类型的使用,public class Student private String name; private Major major; public Student(String name, Major major) this.setName(name); this.setMajor(major); public void setName(String n) name = n; public void setMajor(Major m) major = m; public void display() System.out.println(name + “ is a “ + major.value() + “ major.“); ,40,枚举类型的使用,public class EnumExample public static void main(String args) Student s = new Student(“Fred Schnurd“, Major.CS); s.display(); Output: Fred Schnurd is a Computer Science major. / 如果把display()方法中的major.value()改为major: public void display() System.out.println(name + “ is a “ + major + “ major.“); Output: Fred Schnurd is a CS major.,41,枚举类型的使用,采用枚举类型之后,如果客户代码传入了错误的专业信息,则Java会在编译时进行提示: Student s = new Student(“Fred Schnurd“, “Basketweaving“); Student s = new Student(“Fred Schnurd“, Major.Basketweaving);,42,枚举的另一个例子,public enum Grade A(4.0), B(3.0), C(2.0), D(1.0), F(0.0); private final double value; Grade(double v) value = v; public double value() return value; ,public class GradeDemo public static void main(String args) Grade grade; grade = Grade.A; System.out.println(grade); System.out

温馨提示

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

评论

0/150

提交评论