ファイルから読み取りを行っていますが、try/catch ブロックを使用して例外を処理したいと考えています。私は自分のコードを書きました。しかし、スキャナー オブジェクトを宣言するだけで Eclipse からエラーが発生し、null に初期化する必要がありました。以下に、2 つのバージョンのコードを記述しました。どちらがより良いプラクティスと見なされますか? また、コンストラクター/関数ヘッダーの最後に例外をスローするよりも、try/catch ブロックを使用する方が良いですか?
コード バージョン #1:
java.util.Scanner in = null;
try {
in = new java.util.Scanner (f);
/* use scanner */
} catch (FileNotFoundException e) {
System.err.println("File was not found. Make sure the file exist.");
System.err.println("Message: " + e.getMessage());
} catch (IOException e) {
System.err.println("File could not be opened.");
System.err.println("Message: " + e.getMessage());
} finally {
in.close();
}
コード バージョン #2:
try {
java.util.Scanner in = new java.util.Scanner (f);
/* use scanner */
in.close();
} catch (FileNotFoundException e) {
System.err.println("File was not found. Make sure the file exist.");
System.err.println("Message: " + e.getMessage());
} catch (IOException e) {
System.err.println("File could not be opened.");
System.err.println("Message: " + e.getMessage());
}