Java中异常处理机制解析案例
在Java中,异常处理机制是通过try、catch、finally等关键字来实现的。下面是一个简单的案例解析:
创建一个可能会抛出异常的方法(例如,读取文件内容):
public String readFile(String filePath) {
try {
FileInputStream fis = new FileInputStream(filePath);
byte[] content = new byte[(int)fis.available()]; // 获取剩余可读字节数
fis.read(content); // 读取字节到内容数组
fis.close(); // 关闭文件流,释放资源
return new String(content, "UTF-8")); // 转换为字符串并使用指定编码解码
} catch (FileNotFoundException fnf) {
System.out.println("File not found: " + fnf.getMessage());
return null; // 文件未找到时返回null
} catch (IOException io) {
System.out.println("Error reading file: " + io.getMessage());
return null; // 读取文件错误时返回null
}
}
使用这个方法,如果文件存在但内容为空(例如,文本文件只含有空行),
readFile()
将捕获FileNotFoundException
异常,并在 catch 块中打印错误信息并返回 null。
这就是Java中异常处理机制的一个简单应用案例。
还没有评论,来说两句吧...