### **6. 练习一下。修改下面的方法,使其抛出合适的异常,如FileNotFoundException....etc(10分)**。 ``` public static void cat(File file) throws IOException { RandomAccessFile input = null; String line = null; try { input = new RandomAccessFile(file, "r"); while ((line = input.readLine()) != null) { System.out.println(line); } return; } finally { if (input != null) { input.close(); } } }
时间: 2024-02-14 14:09:26 浏览: 24
修改后的方法如下,可以抛出 `FileNotFoundException` 和 `IOException` 两种异常:
```java
public static void cat(File file) throws FileNotFoundException, IOException {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(file, "r");
while ((line = input.readLine()) != null) {
System.out.println(line);
}
return;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
System.out.println("Failed to close file: " + e.getMessage());
}
}
}
}
```
在 try 块中,如果文件不存在或无法访问,将会抛出 `FileNotFoundException` 异常;而在读取文件时,如果发生读取错误,例如文件格式错误等,将会抛出 `IOException` 异常。此外,在 finally 块中,需要对文件进行关闭操作,因此也需要处理可能引发的 `IOException` 异常。