IO exception handling

JDK7 pre-processing

Use try catch finally to handle exceptions in the stream before java1.7

格式:
    try{
        可能会出现的异常代码
    }catch(异常类变量 变量名){
        异常的处理逻辑
    }finally{
        一定会执行的代码
        资源释放
    }

Code demo:

import java.io.FileWriter;
import java.io.IOException;
public class Demo01TryCatch {
    
    
    public static void main(String[] args) {
    
    
        //提高变量fw的作用域,让finally可以使用
        //变零在定义的时候,可以没有值,但是使用的时候必须有值
        //fw = new FileWriter("day09_IOAndProperties\\f.txt", true);执行失败,fw没有值,fw.close会报错
        FileWriter fw = null;
        try {
    
    
            //可能会出现异常的代码
             fw = new FileWriter("w:\\day09_IOAndProperties\\f.txt", true);
            for (int i = 0; i < 10; i++) {
    
    
                fw.write("Hello" + i + "\r\n");
            }
        }catch (IOException e){
    
    
            //异常的处理逻辑
            System.out.println(e);
        }finally {
    
    
            //一定会执行的代码
            //创建对象失败了,fw的默认值就是null,null是不能调用方法的,会抛出NullPointerException,需要增加一个判断,不是null
            //再把资源释放
           if (fw != null){
    
    
               try {
    
    
                   //fw.close方法声明抛出了IOException异常对象,所以我们就得处理这个异常,要么throws,要么try catch
                   fw.close();
               } catch (IOException e) {
    
    
                   e.printStackTrace();
               }
           }
        }
    }
}

Program demonstration:
Insert picture description here
Insert picture description here

New features of JDK9

The new feature of JDK9
can define the stream object
before the try. The name of the stream object (variable name) can be directly introduced in the ()
after the try . After the try code is executed, the stream object can also be released without writing the finally
introduced object. , It can also be closed automatically without manual close

格式:
    A a = new A();
    B b = new B();
    try(a,b){
        可能会出现异常的代码
    }catch(异常类变量 变量名){
        异常的处理逻辑
    }

Code demo:

public class Demo03JDK9 {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        //1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("D:\\我的文档\\图片11\\1.jpg");
        //2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
        FileOutputStream fos = new FileOutputStream("E:\\1.jpg");
        try (fis;fos){
    
    
            //3.使用字节输入流对象中的方法read读取文件
            int len = 0;
            while((len = fis.read()) != -1){
    
    
                //4.使用字节输出流中的方法write,把读取到的文件写入到目的地文件中
                fos.write(len);
            }
        }catch (IOException e){
    
    
            System.out.println(e);
        }
    }
}

Program demonstration:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/108521871