简体   繁体   English

在try子句中引发异常

[英]Throwing an exception in a try clause

I am doing a project that requires the use of File I/O. 我正在做一个需要使用文件I / O的项目。 The relevant code is as follows: 相关代码如下:

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();

Is it a bad practice to throw the FileNotFoundException simply to put my execution onto another path? 抛出FileNotFoundException只是将我的执行放在另一条路径上是一种不好的做法吗?

What you are doing will "work". 您正在做什么将“工作”。 However, most Java programmers would probably agree that this is an example of using exceptions to implement "normal" flow control. 但是,大多数Java程序员可能会同意,这是一个使用异常来实现“常规”流控制的示例。 It is simpler to write it like this: 像这样写起来更简单:

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();

And that should be rewritten like this to avoid a potential resource leak: 并且应该这样重写,以避免潜在的资源泄漏:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM