文档详情

Delphi数据库基础.doc

发布:2016-09-30约1.56万字共16页下载文档
文本预览下载声明
第5章 异常处理 5.1概述 早期的编程语言比如C语言没有异常处理,通常是遇到错误返回一个特殊的值或设定一个标志,并以此判断是不是有错误产生。随着系统规模的不断扩大,这种错误处理已经成为创建大型可维护程序的障碍。于是在一些语言中出现了异常处理机制,比如Basic中的异常处理语句on error goto”,而Java则在C++基础上建立了新的异常处理机制Java运用面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。这种机制为复杂程序提供了强有力的控制方式。同时这些异常代码与常规代码分离,增强了程序的可读性,编写程序时也显得更灵活。import java.io.*; import java.util.*; public class ReadFile { public static void printFile(String fileName){ //try //{ Vector v=new Vector(); BufferedReader in; String line; in = new BufferedReader(new FileReader(fileName)); line=in.readLine(); while(line!=null){ v.addElement(line); line=in.readLine(); } in.close(); for(int i=0;iv.size();i++) System.out.println(v.elementAt(i)); //} catch(FileNotFoundException e){ // System.out.println(File Not Found+e.getMessage()); //}catch(IOException e){ // System.out.println(IO Exception+e.getMessage()); //} } public static void main(String []args){ ReadFile.printFile(ReadFile.java); } } 类ReadFile中定义了一个静态方法printFile,该方法接收一个文件名作为参数,并在屏幕上打印出文件内容。编译该程序,可以发现出现如下错误: ReadFile.java:7: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown in = new BufferedReader(new FileReader(fileName)); ^ ReadFile.java:8: unreported exception java.io.IOException; must be caught or declared to be thrown String line=in.readLine(); ^ ReadFile.java:11: unreported exception java.io.IOException; must be caught or declared to be thrown line=in.readLine(); ^ ReadFile.java:13: unreported exception java.io.IOException; must be caught or declared to be thrown in.close(); ^ 4 errors 例5.2.1中,粗体表示的5个语句均会出现异常: 首先,BufferedReader的构建器会出现一个FileNotFoundException异常,表示给定的文件不存在。 其次,两条in.readLine()语句和in.close()语句均会出现IOException异常。 最后,v.elementAt(i)也可能出现ArrayIndexOutOfBoundsException异常,表示数组越界。例如当i为负值或是大于v.size()-1时。 观察编译出错信息,可以发现,编译器指出:FileNotFoundException和IOException必须被捕获
显示全部
相似文档