首页 > 解决方案 > 在 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 是一种不好的做法吗?

标签: javaexception-handling

解决方案


你正在做的将“工作”。然而,大多数 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.");
        }
    });
}

推荐阅读