网站大量收购独家精品文档,联系QQ:2885784924

第13章异常捕获和枚举类型重点.ppt

  1. 1、本文档共44页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
* 程序举例 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文件中。 * 程序举例 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类中运作。 * 程序举例 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编译器强制客户代码捕获这个类型的异常。 伪代码 * 程序举例 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 伪代码 此处假设在调用setName之前已经为ssn属性赋了初值。 补充: 枚举类型 * 枚举类型 将变量的取值约束到一个有限的集合。 例如:只希望学位的取值为: Mathematics Biology Chemistry Computer Science Physical Education 为保证客户代码不会传入一个不正确的专业值,因此创造一个自定义异常类型InvalidMajorExcetion,代码如下所示: JDK 1.5 特征 * 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, Cul

文档评论(0)

shuwkb + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档