第4章异常 比京大学计算机系 代亚非
第 4 章 异常 北京大学计算机系 代亚非
第4章异常 4.1异常的概念 4.2异常的分类 4.3捕获异常 4.4声明异常 4.5抛出异常 4.6创造自己的异常 4.7总结
第 4 章 异常 2 4.1 异常的概念 4.2 异常的分类 4.3 捕获异常 4.4 声明异常 4.5 抛出异常 4.6 创造自己的异常 4.7 总结
41异常的概念 什么是异常? 异常实际上是程序中错误导致中断了正 常的指令流的一种事件 没有处理错误的程序: read-file i openTheFile determine its size allocate that much memory closeTheFile
4.1 异常的概念 3 什么是异常? 异常实际上是程序中错误导致中断了正 常的指令流的一种事件. 没有处理错误的程序: read-file { openTheFile; determine its size; allocate that much memory; closeTheFile; }
41异常的概念 以常规方法处理错误 openFiles if (theFilesOpen) t determine the lenth of the file if (gotTheFileLength)( allocate that much memory if (gotEnoughMemory) I read the file into memory if (readFailed) errorCode=-1 else error Code=-2 felse error Code=-3 felse errorCode=-4 ese errorcode=-5
4.1 异常的概念 4 以常规方法处理错误 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;
41异常的概念 观察前面的程序你会发现大部分精力花在 出错处理上了 只把能够想到的错误考虑到,对以外的情况 无法处理 程序可读性差 出错返回信息量太少
4.1 异常的概念 5 观察前面的程序你会发现大部分精力花在 出错处理上了. 只把能够想到的错误考虑到,对以外的情况 无法处理 程序可读性差 出错返回信息量太少