java - 在 try 子句中抛出异常
问题描述
我正在做一个需要使用文件 I/O 的项目。相关代码如下:
Scanner testscn = new Scanner(input).useDelimiter("\n");
testscn.forEachRemaining((scan) -> {
String[] line = scan.split("-");
try {
File img = new File(line[0]);
if (!img.exists()) throw new FileNotFoundException();
test.put(img, line[1].split(","));
} catch (FileNotFoundException e) {
logger.warn("File path " + line[0] + " could not be resolved. Skipping.");
}
});
testscn.close();
仅仅为了将我的执行放到另一条路径上而抛出 FileNotFoundException 是一种不好的做法吗?
解决方案
你正在做的将“工作”。然而,大多数 Java 程序员可能会同意这是使用异常来实现“正常”流控制的一个示例。像这样写它更简单:
Scanner testscn = new Scanner(input).useDelimiter("\n");
testscn.forEachRemaining((scan) -> {
String[] line = scan.split("-");
File img = new File(line[0]);
if (img.exists()) {
test.put(img, line[1].split(","));
} else {
logger.warn("File path " + line[0] + ": Skipping.");
}
});
testscn.close();
应该像这样重写以避免潜在的资源泄漏:
try (Scanner testscn = new Scanner(input).useDelimiter("\n")) {
testscn.forEachRemaining((scan) -> {
String[] line = scan.split("-");
File img = new File(line[0]);
if (img.exists()) {
test.put(img, line[1].split(","));
} else {
logger.warn("File path " + line[0] + ": Skipping.");
}
});
}
推荐阅读
- python - Python - 动态字典的家庭作业
- javascript - 错误:[PrivateRoute] 不是
零件。的所有子组件 必须是 或者 - deployment - 使用 cargo 插件在 payara 上部署
- python - 如何一次终止所有线程
- android - Android Webview打开Chrome浏览器接受Cookie
- linux - 如何增加使用 mmap() 分配的内存区域的大小
- python - 即使在 kivyMD 中提供了 ID,self.root.ids 也是空的
- javascript - 从 PHP 响应发回的同步 Javascript 中的非法令牌,关于跨站点小部件开发
- c++ - C ++选择基于方法的参数的动态类型
- python - 美丽的汤解析中蟒文章发表日期