LoginSignup
0
0

More than 5 years have passed since last update.

JAVA finally

Last updated at Posted at 2015-11-17

■Test07.java

import java.io.FileWriter;
import java.io.IOException;

public class Test07 {

    public static void main(String[] args) throws IOException {
        FileWriter fw = null;
        try {
            fw = new FileWriter("data.txt");
            fw.write("hello!");
        } catch (IOException e) {
            System.out.println("何らかの例外が発生しました");
        } finally {
            fw.close();
        }
    }
}

↑今までこの様にfinallyを態々書いていましたが、
finallyブロックを書かなくても、try-with-resource文を使ってJavaによって自動的にclose()メソッドが呼び出されます。
try-with-resources文

import java.io.FileWriter;
import java.io.IOException;

public class Test04 {
    public static void main(String[] args) {
        try (FileWriter fw = new FileWriter("data.txt");) {
            fw.write("hello!");
        } catch (Exception e) {
            System.out.println("何らかの例外が発生しました");
        }
    }

    public static void subsub() throws IOException {
        FileWriter fw = new FileWriter("data.txt");
    }
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0