在 try 子句中抛出异常

Throwing an exception in a try clause

我正在做一个需要使用文件 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 只是为了将我的执行放到另一条路径上是一种不好的做法吗?

你所做的将"work"。然而,大多数 Java 程序员可能会同意这是一个使用异常来实现 "normal" 流控制的示例。这样写更简单:

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.");
        }
    });
}