Manejo de excepciones IO

Preprocesamiento JDK7

Use try catch finalmente para manejar excepciones en la secuencia antes de java1.7

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

Demostración de código:

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();
               }
           }
        }
    }
}

Demostración del programa:
Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

Nuevas funciones de JDK9

La nueva característica de JDK9
puede definir el objeto de flujo
antes del intento. El nombre del objeto de flujo (nombre de la variable) se puede introducir directamente en ()
después del intento . Después de que se ejecuta el código de intento, el objeto de flujo también se puede liberar sin escribir el
objeto finalmente introducido. , También se puede cerrar automáticamente sin cierre manual

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

Demostración de código:

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);
        }
    }
}

Demostración del programa:
Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/weixin_44664432/article/details/108521871
Recomendado
Clasificación