我在使用 try-and-catch 时经常遇到一些问题:
1) 一些变量需要在 try 括号内声明,否则它们将不在范围内
2) 最终,即使我的 return 语句最终也必须在 try 括号内,但该方法不会返回任何内容。
解决此类问题的正确方法是什么。
导致此问题的方法示例如下。它需要处理 FileNotFoundException 和处理 IOException。我怎样才能最优雅地做到这一点?
public static String getContents (File file) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String contents = new String();
while (reader.ready())
contents += reader.readLine();
return contents;
}