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
- Exception
- Exception
- Exception
- exception
- Exception
- Exception
- Exception
- exception
- Exception
- Exception
- Exception
- Exception
- exception
- exception
- exception
- Exception
- Exception
- Exception
- OpenCV入门教程(3)-Mat类之选取图像局部区域
- 基于itop4412在Linux最小系统下的USB摄像头采集视频的H264编码
- JS遍历属性和方法
- 固高运动控制器-vs2008远程调试wince心得_1
- 光缆类型
- Exception
- Python 切片(slice)
- 四:Java语言基础组成—— 常量和变量
- 关于安装两个jdk的问题
- :3个瓶盖可以换一瓶可乐,一共有28个人,要保证每个人一瓶,请问最低需要买多少瓶可乐呢?
- Python 正则表达式
- (三十六)终端
- [APR]Core Utilization和Cell Utilization的区别
- js改变style样式和css样式