Ank*_*kur 2 java exception-handling try-catch
使用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;
}
Run Code Online (Sandbox Code Playgroud)
coo*_*ird 10
如果在getContents方法中不需要进行异常处理,还有一个选项- 向方法添加一个throws子句以使该方法抛出异常:
public static String getContents (File file)
throws IOException, FileNotFoundException {
Run Code Online (Sandbox Code Playgroud)
这样,调用方法的代码将处理Exceptions而不是方法本身.如果s被抛出到调用它的方法,那么该方法中不需要try/ catchblocks Exception.
这可能是也可能不是处理该情况的理想方式,这取决于预期方法的行为方式.
编辑
经过深思熟虑,让方法抛出异常可能是一个好主意.我认为D.Shawley的评论我认为总结得很好 - "异常处理应该意味着只处理有意义的异常."
在这种情况下,该getContents方法似乎获取指定的内容File,并将a返回String给调用者.
如果要在该getConents方法中执行异常处理,则传达发生错误的唯一方法是返回某种预定值,例如null向调用者返回以通知发生错误.
但是,通过让方法本身将一个异常抛回给调用者,调用者可以选择相应的反应:
try {
String contents = getContents(new File("input.file"));
} catch (IOException ioe) {
// Perform exception handling for IOException.
} catch (FileNotFoundException fnfe) {
// Inform user that file was not found.
// Perhaps prompt the user for an alternate file name and try again?
}
Run Code Online (Sandbox Code Playgroud)
不是让setContents方法提出自己的协议来通知发生错误,而是抛出IOException和FileNotFoundException返回方法调用者可能会更好,因此异常处理可以在适当的替代操作可以采取的地方执行地点.
只有在可以进行某些有意义的处理时才应执行异常处理.
你可以按如下方式处理它:
StringBuilder contents = new StringBuilder();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
while (reader.ready()) {
contents.append(reader.readLine());
}
} catch (FileNotFoundException fne) {
log.warn("File Not Found", fne);
} catch (IOException ioe) {
log.warn("IOException", ioe);
}
return contents.toString();
Run Code Online (Sandbox Code Playgroud)
您应该在上面的情况下使用StringBuilder而不是String,但在性能方面要好得多.