2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JAVA 自動的にclose();が呼び出されるtry-catch文

Last updated at Posted at 2015-11-16

tryの直後に丸かっこで囲まれた複数の文を記述することが可能

開かれたファイルやデータベース接続などは、finallyブロックを記述しなくても自動的にclose()メソッドが呼び出される

■例

import java.io.FileWriter;

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("何らかの例外が発生しました");
		}
	}
}

■close();が呼び出されずに終了してしまう例

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

public class Test05 {
	public static void main(String[] args) {
		try {
			FileWriter fw = new FileWriter("data.txt");
			fw.write("hello!");
			fw.close();

		} catch (IOException e) {
			System.out.println("書き込みが失敗しました");
			System.exit(1);
		} catch (NullPointerException e) {
			System.out.println("nullです");
			System.exit(2);
		}
	}
}
2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?