黑马程序员技术交流社区

标题: IO异常的处理方式 [打印本页]

作者: l6781155    时间: 2015-7-9 09:28
标题: IO异常的处理方式
一定要关闭资源,所以close方法放在finally中
close方法也会抛出异常,所以close要单独try catch一次,
并且要判断当对象创建成功时才能调用close,否则将会抛出异常
如果有多个文件需要关闭,要分别判断每一个是否为空
  1. package com.mytest;

  2. import java.io.FileWriter;
  3. import java.io.IOException;

  4. public class test02 {
  5. public static void main(String[] args) {

  6. FileWriter fw = null;
  7. try {

  8. fw = new FileWriter("Demo.txt");

  9. fw.write("hello IO");

  10. } catch (IOException e) {

  11. System.out.println(e.toString());
  12. } finally {

  13. try {
  14. // 如果文件没创建成功,fw调用close方法将会出现异常
  15. if (fw != null) {

  16. fw.close();
  17. }
  18. } catch (IOException e) {

  19. e.printStackTrace();
  20. }
  21. }

  22. }

  23. }
复制代码

作者: dajiaoya    时间: 2015-7-9 10:04
分享快乐,赞一个




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2