第6章异常处理 理解异常和异常处理 区别异常的类型: Error与 Exception,必检异常与免检异常 在方法头中声明异常 在方法中抛出异常 o/用try- catch块处理异常 了解异常的传播 o在try- catch块中重新抛出异常 o在try- catch块中使用 finally.子句 o了解何时使用异常 o声明自定义异常类
理解异常和异常处理 区别异常的类型:Error与Exception,必检异常与免检异常 在方法头中声明异常 在方法中抛出异常 用try-catch块处理异常 了解异常的传播 在try-catch块中重新抛出异常 在try-catch块中使用finally子句 了解何时使用异常 声明自定义异常类 第6章 异常处理
程序错误:语法错误、运行错误、逻辑错误 浯法错误是指代码没有遵循语言的规则,可以由编 器检查发现。 o在程序运行过程中,如果环境发现一个不可能执行 的操作,就会出现运行错误。 o如果程序没有按照预期的方案执行,就会发生逻辑 错误
程序错误:语法错误、运行错误、逻辑错误 语法错误是指代码没有遵循语言的规则,可以由编 译器检查发现。 在程序运行过程中,如果环境发现一个不可能执行 的操作,就会出现运行错误。 如果程序没有按照预期的方案执行,就会发生逻辑 错误
Runtime errors import javax. swing. JOptionPane public class Test i public static void main(string[] args)i String input JOptionPane showInputDialog(null, nPlease enter an integer )i nt number Integer parseInt (input)i 如果这行出现异常,就会跳过 // Display the result 该方法中其余的行,程序终止 JOptionPane showMessageDialog(null, u The number entered is "+ number)i System. exit(o)i V程序结束
Runtime Errors import javax.swing.JOptionPane; public class Test { public static void main(String[] args) { String input = JOptionPane.showInputDialog(null, "Please enter an integer"); int number = Integer.parseInt(input); // Display the result JOptionPane.showMessageDialog(null, "The number entered is " + number); System.exit(0); } } 如果这行出现异常,就会跳过 该方法 中其余的行,程序终止 程序结束
程序 readfile(自然语言描述) readFile open the file determine its size allocate the much memory read the file into memory close the file
程序readFile(自然语言描述) readFile{ open the file; determine its size; allocate the much memory; read the file into memory; close the file; }
传统错误处理:通过函数返回值 readFile initialize errorcode=0i open the filei the Fileopen) determine its size if(getTheFileLenght t allocate the much memory; if(getEnough Memory read the file into memory: (readFailed) errorCode=-1 } felse t error Code=-2: felse t errorCode=-3: close the file if(the FildDidntclose & errorCode==ort errorcode 4 felse t errorCode else t errorCode=-6: return errorCode
传统错误处理:通过函数返回值 readFile{ initialize errorCode=0; open the file; if(theFilesOpen){ determine its size; if(getTheFileLenght){ allocate the much memory; if(getEnoughMemory){ read the file into memory; if(readFailed){ errorCode=-1; } }else { errorCode=-2; } }else { errorCode=-3; } close the file; if(theFildDidntClose && errorCode==0){ errorCode=-4; }else { errorCode=-5; } } else { errorCode=-6; } return errorCode; }