异常102北大计算机系java培训讲义_1课件_第1页
异常102北大计算机系java培训讲义_1课件_第2页
异常102北大计算机系java培训讲义_1课件_第3页
异常102北大计算机系java培训讲义_1课件_第4页
异常102北大计算机系java培训讲义_1课件_第5页
已阅读5页,还剩32页未读 继续免费阅读

下载本文档

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

文档简介

第 4 章 异常 北京大学计算机系 代亚非 n本资源由 寒秀草与巧克力 搜集与网络 n请您在传播的时候将下载分数设为0 n真正体现资源共享的理念 n谢谢 n更多0分资料去我的文库 2 3第4章 异常 n4.1 异常的概念 n4.2 异常的分类 n4.3 捕获异常 n4.4 声明异常 n4.5 抛出异常 n4.6 创造自己的异常 n4.7 总结 44.1 异常的概念 n什么是异常? 异常实际上是程序中错误导致中断了正常 的指令流的一种事件. n没有处理错误的程序: read-file openTheFile; determine its size; allocate that much memory; closeTheFile; 5 4.1 异常的概念 n以常规方法处理错误 openFiles; if (theFilesOpen) determine the lenth of the file; if (gotTheFileLength) allocate that much memory; if (gotEnoughMemory) read the file into memory; if (readFailed) errorCode=-1; else errorCode=-2; else errorCode=-3; else errorCode=-4 ; else errorCode=-5; 64.1 异常的概念 n观察前面的程序你会发现大部分精力花在 出错处理上了. n只把能够想到的错误考虑到,对以外的情况 无法处理 n程序可读性差 n出错返回信息量太少 74.1 异常的概念 n用异常的形式处理错误 read-File; try openTheFile; determine its size; allocate that much memory; closeTheFile; catch(fileopenFailed) dosomething; catch(sizeDetermineFailed) dosomething; catch(memoryAllocateFailed) dosomething; catch(readFailed) dosomething; catch(fileCloseFailed) dosomething; 84.1 异常的概念 n和传统的方法比较异常的优点: 1.把错误代码从常规代码中分离出来 2. 把错误传播给调 用堆栈 3. 按错误类型和 错误差别分组 4. 系统提供了对于一些无法预测的错误的 捕获和处理 5. 克服了传统方法的错误信息有限的问题 method1 method2 method3 method4产生异常 传 递 处理异常 94.1 异常的概念 n. class ExcepTest public void main(String args) int b=0; int a; try a=4/b; catch(ArithmeticException e) System.out.println(“divided by 0”); try URL url=new URL(/”,”hit.gif”); catch(MalformedURLEception e) badURL=true; repaint(); 104.2 异常的分类 n异常是一个对象,它继承自Throwable类,所有的 Throwable类的子孙类所产生的对象都是例外. nError:由Java虚拟机生成并抛出,Java程序不做 处理. nRuntime Exception(被0除等系统错误,数组下 标超范围):由系统检测, 用户的Java 程序可不做 处理,系统将它们交给缺省的异常处理程序. nException(程序中的问题,可预知的): Java编译 器要求Java程序必须捕获或声明所有的非运行时 异常 nthrow:用户自己产生异常 11 4.2 异常的分类 n.Throwable Error Exception RuntimeException 缺省的异常 处理程序 由用户捕获或 声明并处理 不做处理 用户自己产生的异常 要处理 12 4.3 捕获异常 n捕获并处理异常 try /接受监视的程序块,在此区域内发生 /的异常,由catch中指定的程序处理; catch(要处理的异常种类和标识符) /处理异常; catch(要处理的异常种类和标识符) /处理异常; 134.3 捕获异常 n常见的异常 nArithmeticException nArrayIndexOutOfBandsException nArrayStoreException nIOException nFileNotFoundException nNullPointerException nMalformedURLException nNumberFormatException nOutOfMemoryException 如果在使用能够 产生异常的方法 而没有捕获和处 理,将不能通过 编译 144.3 捕获异常 n例:编写Java程序,包含三种异常 n算术异常, 字符串越界,数组越界 n观察输出信息: n每个异常对象可以直接给出信息 154.3 捕获异常 class first_exception public static void main(String args) char c; int a,b=0;int array=new int7; String s=“Hello“; try a=1/b; catch(ArithmeticException ae) System.out.println(“Catch “+ae); try array8=0; catch(ArrayIndexOutOfBoundsException ai) System.out.println(“Catch “+ai); try c=s.charAt(8); catch(StringIndexOutOfBoundsException se) System.out.println(“Catch “+se); 164.3 捕获异常 l一定会执行的程序块-finally 异常处理的统一出口 try /常规的代码; catch() /处理异常 finally /不论发生什么异常(或者不发生任何异 常),都要执行的部分; 174.3 捕获异常 nfinally在文件处理时非常有用 ntry n 对文件进行处理的程序; ncatch(IOException e) n /对文件异常进行处理; nfinally n 不论是否发生异常,都关闭文件; n 184.4 声明异常 n一个方法不处理它产生的异常,而是沿着调用层次 向上传递,由调用它的方法来处理这些异常,叫声 明异常. l声明异常的方法 l在产生异常的方法名后面加上要抛出(throws)的 异常的列表 nvoid compute(int x)throws ArithmeticException nreturnType methodName(parameterlist) throws exceptionList 194.4 声明异常 例:若因 某种原 因不想 在创建 URL的 方法中 处理异 常 public method1() int x; try x=System.in.read(); compute(x); catch(IOException ioe) System.out.println(“read error”); catch(ArithmeticException e) System.out.println(“devided by 0”); public int compute(int x) throws ArithmeticException e) return z=100/x; 204.4 声明异常 method1 computer 异常 抛出 处理 214.4 声明异常 例:说出程序执行结果 public class exception1 void Proc(int sel) throws ArithmeticException, ArrayIndexOutOfBoundsException System.out.println(“In Situation“ + sel ); if (sel=0) System.out.println(“no Exception caught“); return; else if(sel=1) int iArray=new int4; iArray10=3; 22 4.4 声明异常 public static void main(String args) try Proc(0); Proc(1); catch(ArrayIndexOutOfBoundsException e) System.out.println(“Catch“+e); c:jview throwsException In Situation 0 no Exception caught In Situation 1 Catch java.lang.ArrayIndexOutOfBoundsException:10 234.5 抛出异常 l抛弃异常: 不是出错产生,而是人为地抛出 nthrow ThrowableObject; nthrow new ArithmeticException(); n例:编写程序人为抛出(JavaThrow.prj) ArithmeticException, ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException A methodException Another method throw caught 244.5 抛出异常 class JavaThrow public static void main(String args) try throw new ArithmeticException(); catch(ArithmeticException ae) System.out.println(ae); try throw new ArrayIndexOutOfBoundsException(); catch(ArrayIndexOutOfBoundsException ai) System.out.println(ai); try throw new StringIndexOutOfBoundsException(); catch(StringIndexOutOfBoundsException si) System.out.println(si); 254.6 创造自己的异常 n不是由Java系统监测到的异常(下标越界,被 0-除等),而是由用户自己定义的异常. n用户定义的异常同样要用try-catch捕获,但 必须由用户自己抛出 throw new MyException. n异常是一个类,用户定义的异常必须继承自 Throwable或Exception类,建议用 Exception类. 264.6 创造自己的异常 n形如: nclass MyException extends Exception n.; n例1 :计算两个数之和,当任意一个数超出范围时, 抛出自己的异常 public class NumberRangeException extends Exception public NumberRangeException(String msg) super(msg); 274.6 创造自己的异常 n. public boolean action(Event evt, Object arg) try int answer = CalcAnswer(); answerStr = String.valueOf(answer); catch (NumberRangeException e) answerStr = e.getMessage(); repaint(); return true; 284.6 创造自己的异常 n. public int CalcAnswer() throws NumberRangeException int int1, int2; int answer = -1; String str1 = textField1.getText(); String str2 = textField2.getText(); try int1 = Integer.parseInt(str1); int2 = Integer.parseInt(str2); if (int1 20) | (int2 20) NumberRangeException e = new NumberRangeException (”Numbers not within the specified range.“); throw e; answer = int1 + int2; catch (NumberFormatException e) answerStr = e.toString(); return answer; 294.6 创造自己的异常 n例2 :在定义银行类时,若取钱数大于余额 则作为异常处理 (InsufficientFundsException). n思路:产生异常的条件是余额少于取额, 因 此是否抛出异常要判断条件 n取钱是withdrawal方法中定义的动作,因 此在该方法中产生异常. n处理异常安排在调用withdrawal的时候, 因此withdrawal方法要声明异常,由上级 方法调用 n要定义好自己的异常类 304.6 创造自己的异常 n. class Bank double balance; public void deposite(double dAmount) if(dAmount0.0) balance+=dAmount; public void withdrawal(double dAmount) throws InsufficientFundsException if (balancedAmout) throw new InsufficientFundsException(this,dAmount); balance=balance-dAmount; public void show_balance() System.out.println(“The balance is “+(int)balance); 314.6 创造自己的异常 public class ExceptionDemo public static void main(String args) try Bank ba=new Bank(50); ba.withdrawal(100); System.out.println(“Withdrawal successful!”); catch(Exception e) System.out.println(e.toString(); 324.6 创造自己的异常 n.public class InsufficientFundsException extends Exception private Bank excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; public String excepMesagge() String str=“The balance”+ excepbank.showBalance()+ “The withdrawal was”+excepAmount; return str; 334.7 小结 1.一般格式:正常程序和出错处理分离开来 try Java statement; catche(ExceptionType1 ExceptionObject) Exception1 handling; catche(ExceptionType2 ExceptionObject) Exception2 handling; . finally final handli

温馨提示

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

评论

0/150

提交评论