《面向对象程序设计》异常处理.ppt

  1. 1、本文档共43页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
throws 如果一个方法可以导致一个异常但不处理它,它必须指定这种行为以使方法的调用者可以保护它们自己而不发生异常。 做到这点你可以在方法声明中包含一个throws子句。 一个throws 子句列举了一个方法可能引发的所有异常类型。一个方法可以引发的所有其他类型的异常必须在throws子句中声明。如果不这样做,将会导致编译错误。 public class z1 { public static void f( ) throws Exception{ throw new Exception("This is my test Exception"); } public static void g( ) throws Exception { f( ); System.out.println("the code after f() call"); } public static void main(String[] args) { try { g( ); System.out.println("the code after g() call"); } catch(Exception e) { System.out.println("caught exception here "); System.out.println("e.getMessage(): "+e.getMessage()); System.out.println("e.toString: "+e.toString()); System.out.println("e.printStackTrace: "); e.printStackTrace(); } } } f() g() 入口main() JVM通过创建调用 栈来记录各个方法 被调用的顺序 g() 入口main() 当方法f()执行完毕 退出时,从调用栈 中将其删除 Exception object information Exception objects have a group of methods common to them all. String getMessage( ) Obtains the argument that was passed to the constructor of the exception object. String toString( ) The name of the exception (its type), followed by a colon ( : ), followed by the String returned by method getMessage. void?printStackTrace( ). This method displays the String returned by method toString, followed by information that shows the sequence of methods that were called before the exception was thrown. For example 上例 定义异常类 尽管Java的内置异常处理大多数常见错误,你也许希望建立你自己的异常类型来处理你所应用的特殊情况。这是非常简单的:只要定义Exception的一个子类就可以了(Exception当然是Throwable的一个子类)。 你的子类不需要实际执行什么——它们在类型系统中的存在允许你把它们当成异常使用。Exception类自己没有定义任何方法。当然,它继承了Throwable提供的一些方法。因此,所有异常,包括你创建的,都可以获得Throwable定义的方法。这些方法显示在表3中。你还可以在你创建的异常类中覆盖一个或多个这样的方法。 计算一个数字的平方根 class OutOfRangeException extends Exception { public OutOfRangeException

文档评论(0)

today-is-pqsczlx + 关注
实名认证
内容提供者

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

1亿VIP精品文档

相关文档