java 异常处理向处机制笔记

package eight;

import java.io.*;

/**
 * @author KuKaFei.Hai
 * @date 2020/4/14 : 16:50
 * @Email : 383232084@qq.com
 */
public class exceptionMode {
    public static void main(String[] args) {

    }

    /**
     * JDK 9 后的改进方案 虽然try()里面的写法简单了,但是,还是要抛出一个异常,所以,推荐 copyFileB 的方法
     * try(.....){
     *
     * }catch(){
     *
     * }
     */
    private static  void copyFileC() throws IOException {
        FileReader fr = new FileReader("test.txt");
        FileWriter fw = new FileWriter("text.txt");
        try(fr;fw){
            char[] bytBox = new char[1024];
            int flag;
            while ((flag = fr.read()) != -1) {
                fw.write(bytBox, 0, flag);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    /**
     * 推荐☆☆☆☆☆
     * JDK 7 后的改进方案
     * 自动释放流资源,不用写 finally,也不用抛异常
     */
    private static  void copyFileB(){
        try(FileReader fr = new FileReader("test.txt");
            FileWriter fw = new FileWriter("text.txt");){
            char[] bytBox = new char[1024];
            int flag;
            while ((flag = fr.read()) != -1) {
                fw.write(bytBox, 0, flag);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    /**
     * //try....catch...finally 处理异常,过于麻烦
     */
    private static void copyFileA(){
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("test.txt");
            fw = new FileWriter("text.txt");
            char[] bytBox = new char[1024];
            int flag;
            while ((flag = fr.read()) != -1) {
                fw.write(bytBox, 0, flag);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    /**
     * @throws IOException 这里只是抛出异常,并没有处理异常
     */
    private static void copyFile() throws IOException {
        FileReader fr = new FileReader("test.txt");
        FileWriter fw = new FileWriter("text.txt");
        char[] bytBox = new char[1024];
        int flag;
        while ((flag = fr.read()) != -1) {
            fw.write(bytBox, 0, flag);
        }
        fr.close();
        fw.close();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值