JAva関流の正しい姿勢

3650 ワード

###エラー例1
public void CopyFile() {
        FileReader fr = null;
        FileWriter fw = null;

        try {

            fr = new FileReader("c:\\xy1.txt"); // ①
            fw = new FileWriter("c:\\xy2.txt"); // ②

            char[] charBuffer = new char[1024];
            int len = 0;
            while ((len = fr.read(charBuffer)) != -1) {
                fw.write(charBuffer, 0, len);
            }
            System.out.println("      ");

        } catch (IOException e) {
            throw new RuntimeException("        ");
        } finally {
            try {
                fr.close(); // ③
                fw.close(); // ④
            } catch (IOException e) {
                throw new RuntimeException("    ");
            }
        }
    }```

 ①     ,fr        ,  ③           。②④       。

####    2

public void CopyFile() { FileReader fr = null; FileWriter fw = null;
    try {

        fr = new FileReader("c:\\xy1.txt"); // ①
        fw = new FileWriter("c:\\xy2.txt"); // ②

        char[] charBuffer = new char[1024];
        int len = 0;
        while ((len = fr.read(charBuffer)) != -1) {
            fw.write(charBuffer, 0, len);
        }
        System.out.println("      ");
    } catch (IOException e) {
        throw new RuntimeException("        ");
    } finally {
        try {
            if (null != fr) {
                fr.close(); // ③
            }
            if (null != fw) {
                fw.close(); // ④
            }

        } catch (IOException e) {
            throw new RuntimeException("    "); // ⑤
        }
    }
}```

空かどうかの判断を加えることで、空ポインタの異常を回避できます.ただし、③の実行エラーが発生すると、プログラムはそのまま⑤に入り、④はまったく実行されず、閉じることができなくなります.
####正しいシャットダウン姿勢:
 public void CopyFile() {
        FileReader fr = null;
        FileWriter fw = null;

        try {
            fr = new FileReader("c:\\xy1.txt");
            fw = new FileWriter("c:\\xy2.txt");
           
            char[] charBuffer = new char[1024];
            int len = 0;
            while ((len = fr.read(charBuffer)) != -1) {
                fw.write(charBuffer, 0, len);
            }
            System.out.println("      ");
        } catch (IOException e) {
            throw new RuntimeException("        ");
        } finally {
            try {
                if (null != fr) {
                    fr.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("    ");
            }

            try {
                if (null != fw) {
                    fw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("    ");
            }
        }
    }