有没有办法在不破坏Java循环的情况下捕获异常?

时间:2013-05-02 20:29:01

标签: java loops exception-handling

在Java中,如果可以在while循环中抛出异常,则在try-catch块包围的循环与循环内的try-catch块包围的语句之间存在差异。

例如,以下代码段不同:


代码段1:

try {
    for (File file : files) {
        FileInputStream fis = new FileInputStream(file);
        System.out.println("OK!");
    }
}
catch (FileNotFoundException exc) {
    System.out.println("Error!");
}

^如果抛出 FileNotFoundException ,此代码段会中断循环。因此,如果无法读取文件,则循环中断,Java将停止读取更多文件。


代码段2:

for (File file : files) {
    try {
        FileInputStream fis = new FileInputStream(file);
        System.out.println("OK!");
    }
    catch (FileNotFoundException exc) {
        System.out.println("Error!");
    }
}

^如果抛出异常,此代码段不会中断循环,如果发生异常,代码会捕获异常并继续 files 中的下一个元素。换句话说,它不会停止读取文件。


现在我想要读取某个目录中的某个文件(比如 bananas.xml ),如果该文件是否可读则不予审阅 - 该XML文件是元数据文件,可能不是要运行程序,请阅读相应的目录(香蕉):

File main = new File("/home/MCEmperor/test");
File fruitMeta = new File(main, "bananas.xml");
FileInputStream fruitInputStream = new FileInputStream(fruitMeta); // This code COULD throw a FileNotFoundException
// Do something with the fruitInputStream...

File fruitDir = new File(main, "bananas");
if (fruitDir.exists() && fruitDir.canRead()) {
    File[] listBananas = fruitDir.listFiles();
    for (File file : listBananas) {
        FileInputStream fis = new FileInputStream(file); // This code COULD throws a FileNotFoundException
        // Do something with the fis...
    }
}

现在,上面代码段中的两行可能会抛出FileNotFoundException而我不想破坏循环。

现在有一种方法可以制作一个try-catch块,如果抛出异常但捕获两行,但不会破坏for - 循环?

1 个答案:

答案 0 :(得分:4)

这样的事情怎么样?

FileInputStream fruitInputStream = getFileInputStream(fruitMeta);
...
fis = getFileInputStream(file);

private static FileInputStream getFileInputStream(File file) {
    try {
        return new FileInputStream(file);
    catch(FileNotFoundException e) {
        return null;
    }
}
相关问题