面试题答案
一键面试1. 使用try-catch块捕获异常
通过try-catch
块来捕获可能抛出的IOException
,并在catch
块中进行相应的处理。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExceptionHandlingExample1 {
public static void main(String[] args) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("example.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("读取文件时发生错误: " + e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
System.out.println("关闭流时发生错误: " + e.getMessage());
}
}
}
}
}
2. 抛出异常
在方法签名中声明抛出IOException
,让调用该方法的上层代码来处理异常。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExceptionHandlingExample2 {
public static void readFile() throws IOException {
InputStream inputStream = new FileInputStream("example.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("读取文件时发生错误: " + e.getMessage());
}
}
}