java_core基础篇概要.ppt
文本预览下载声明
捕获异常 finally 捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分以前,能够对程序的状态作统一的管理。不论在try、catch代码块中是否发生了异常事件,finally块中的语句都会被执行。 finally语句是可选的 5.3 运行时异常和编译时异常 前面但使用的异常都是RuntimeException类或是它的子类,这些类的异常的特点是:即使没有使用try和catch捕获,Java自己也能捕获,并且编译通过 ( 但运行时会发生异常使得程序运行终止 )。 如果抛出的异常是IOException类的异常,则必须捕获,否则编译错误。 5.4 IOException 异常处理举例 import java.io.*; public class Test{ public static void main(String[] args) { FileInputStream in=new FileInputStream(myfile.txt); int b; b = in.read(); while(b!= -1) { System.out.print((char)b); b = in.read(); } in.close(); } } IOException 异常处理举例 import java.io.*; public class Test{ public static void main(String[] args){ try{ FileInputStream in=new FileInputStream(myfile.txt); int b; b = in.read(); while(b!= -1) { System.out.print((char)b); b = in.read(); } in.close(); }catch (IOException e) { System.out.println(e); }finally { System.out.println( It’s ok!); } } } 5.5 声明抛出异常 声明抛出异常是Java中处理异常的第二种方式 如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显式地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。 在方法声明中用 throws 子句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。 声明抛出异常举例: public void readFile(String file) throws FileNotFoundException { …… // 读文件的操作可能产生FileNotFoundException类型的异常 FileInputStream fis = new FileInputStream(file); ..…… } 5.6 声明抛出异常示例 import java.io.*; public class Test{ public static void main(String[] args){ Test8_5 t = new Test8_5(); try{ t.readFile(); }catch(IOException e){ } } public void readFile()throws IOException { FileInputStream in=new FileInputStream(myfile.txt); int b; b = in.read(); while(b!= -1) { System.out.print((char)b); b = in.read(); } in.close(); } } 5.7 重写方法声明抛出异常原则 重写方法不能抛出比被重写方法范围更大的异常类型 public class A { public void methodA() throws IOException { …… } } public class B1 extends A { publi
显示全部