Exception

来源:互联网 发布:windows控制台命令 编辑:程序博客网 时间:2024/06/08 09:37
import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class TestReadFile {public static void main(String[] args) {FileReader reader=null;try{reader=new FileReader("d:/a.txt");char a=(char)reader.read();char a2=(char)reader.read();System.out.println(""+a+a2);} catch(FileNotFoundException e){e.printStackTrace();}catch (IOException e) {                      /*不能交换位置,否则会报错Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOExceptionFileNotFoundException 是 IOException的一个子类,子类放前面,父类放后面*/e.printStackTrace(); }finally{                     //一般在finally里面要关闭资源try {if(reader!=null){reader.close();}} catch (IOException e) {e.printStackTrace();}}}}

try  catch  finally  return 的执行顺序:

1.执行try ,catch,给定返回值

2.执行finally

3.return

例:

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class TestReadFile {public static void main(String[] args) {String str =new TestReadFile().openFile();System.out.println(str);}String openFile(){try {System.out.println("aaa");FileInputStream fis=new FileInputStream("d:/a.txt");int a =fis.read();System.out.println("bbb");return "step1";} catch (FileNotFoundException e) {System.out.println("catching!!!!!!");e.printStackTrace();return "step2";          //先确定返回的值,并不会直接结束运行} catch (IOException e) {e.printStackTrace();return "step 3";}finally{System.out.println("finally!!!");//return "fff";            //不要在finally中使用return}}}
运行结果:
aaabbbfinally!!!step1


0 0
原创粉丝点击