这是简化的代码:
hidden
在两种情况下,我们可能会得到public static void cat(File file) {
try (RandomAccessFile input = new RandomAccessFile(file, "r")){
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
return;
} catch(FileNotFoundException a){
;//do something to recover from this exception.
}catch(IOException b){
;//distinguish between close and readLine exception.
}
}
:
IOEception
以外,其他所有方法都可以正常工作。input
抛出并readLine
那么如何区分这两种情况?有什么好的方法吗?还是应该简化一下异常消息的字符串比较以区分这两个IOException.
?
谢谢!我只是找不到简单的方法来做到这一点。
答案 0 :(得分:0)
您可以在返回前进行标记
public static void cat(File file) {
boolean readAll = false;
try (RandomAccessFile input = new RandomAccessFile(file, "r")){
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
readAll = true;
return;
} catch(FileNotFoundException a){
;//do something to recover from this exception.
}catch(IOException b){
;//distinguish between close and readLine exception.
if (readAll) ...
}
}