1

In Java, there's a difference between a loop surrounded with a try-catch block if an exception could be thrown inside the while loop, and a statement surrounded by a try-catch block inside a loop.

For instance, the following code snippets are different:


Snippet 1:

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

^This code snippet breaks the loop if a FileNotFoundException is thrown. So if a file cannot be read, then the loop breaks and Java will stop reading further files.


Snippet 2:

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

^This code snippet does not break the loop if an exception is thrown, if an exception occurs, the code catches the exception and continues to the next element in files. With other words, it won't stop reading the files.


Now I want to read a certain file in a directory (say bananas.xml), and, unregarded if that file is readable or not—the XML file is a metadata file, which might not be required for the program to run—, read the corresponding directory (which is bananas):

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...
    }
}

Now two lines in the snippet above may throw a FileNotFoundException and I don't want to break the loop.

Now is there a way to make one try-catch block with catches both lines if an exception is thrown, but without breaking the for-loop?

4

1 回答 1

4

这样的事情怎么样?

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

private static FileInputStream getFileInputStream(File file) {
    try {
        return new FileInputStream(file);
    catch(FileNotFoundException e) {
        return null;
    }
}
于 2013-05-02T20:35:44.173 回答