【发布时间】:2009-06-15 04:42:10
【问题描述】:
我在使用 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;
}
【问题讨论】:
标签: java exception-handling try-catch