我正在从文件中读取数据,并且我想使用 try/catch 块来处理异常。我写了我的代码。但是,eclipse 只声明了我的扫描仪对象就给了我一个错误,我不得不将它初始化为 null。下面我写了我的代码的两个版本。哪个被认为是更好的做法?此外,使用 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());
}