必须被抛出的异常.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
必须被抛出的异常

Chapter 7 异常 Exceptions Objectives 定义异常(exceptions) 使用 try, catch, finally 语句 异常分类 常见异常 用户自定义异常 Exceptions Exception类用于定义判断程序中可能出错的条件 异常发生的情况: 打开文件时,发现文件不存在 网络阻塞 操作数值不在定义范围 找不到要加载的类 由Error类定义的错误对象 Exception Example public class HelloWorld { public static void main (String args[]) { int i = 0; String greetings [ ] = { Hello world!, No, I mean it!, HELLO WORLD!! }; while (i 4) { System.out.println (greetings[i]); i++; } } } Try/catch 语法 try { // code that might throw a particular exception } catch (MyExceptionType myExcept) { // code to execute if a MyExceptionType exception is thrown } catch (Exception otherExcept) { // code to execute if a general Exception exception is thrown } 异常处理原则 如果异常A没有在当前的try-catch模块处理, 则异常A 被抛出(throw)给调用当前方法A的方法B. 如果异常A 被抛给main()后还没有被处理,则程序被终止 finally Statement try { startFaucet(); waterLawn(); } catch (BrokenPipeException e) { logProblem(e); } finally { stopFaucet(); } Exception Example Exception类 常见Exceptions ArithmeticException NullPointerException NegativeArraySizeException ArrayIndexOutOfBoundsException SecurityException 声明异常和处理异常 try-catch-finally模块处理异常 使用throws语句来声明异常 方法如果存在异常,并且不在方法内部进行处理,就一定要声明抛出异常 Runtime时的系统异常或错误不用处理或声明 public void readDatabaseFile(String file) throws FileNotFoundException, UTFDataFormatException { // open file stream; may cause FileNotFoundException FileInputStream fis = new FileInputStream(file); // read a string from fis may cause UTFDataFormatException... } 抛出异常的方法 必须被抛出的异常: 原方法抛出的异常 原方法抛出异常类的子类异常 如父类方法抛出多个异常,其重写方法抛出的异常为该异常集合的真子集 Examples Examples Con. 自定义异常类 处理自定义异常 Tasks: use the try-catch block to handle a simple run-time exception. create an OverdraftException that is thrown by the withdraw method in the Account class. * * * *

文档评论(0)

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

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

1亿VIP精品文档

相关文档