2 years ago

#77565

test-img

Jam

Equivalent of try-with-resources but throw the exception

I have a function read:

public static ArrayList<String> read(Path path) throws FileNotFoundException {
        ArrayList<String> lines = new ArrayList<String>();
        File fileToRead = path.toFile();
        Scanner fileReader = new Scanner(fileToRead);
        while (fileReader.hasNext()) {
            lines.add(fileReader.nextLine());
        }
        fileReader.close();

        return lines;
    }

I want it to pass on a FileNotFoundException if it encounters one, but I'm not sure if encountering this exception while creating the scanner will result in an unclosed scanner.

I'd like to implement a similar behavior that the try-with-resources block provides as shown below, but without catching and re-throwing the error (unless this is the intended solution).

public static ArrayList<String> read(Path path) throws FileNotFoundException {
        ArrayList<String> lines = new ArrayList<String>();
        File fileToRead = path.toFile();
        
        try (
            Scanner fileReader = new Scanner(fileToRead);
        ) {
            while (fileReader.hasNext()) {
                lines.add(fileReader.nextLine());
            }
        }
        catch (FileNotFoundException e) {
            throw e;
        }

        return lines;
    }

java

try-with-resources

0 Answers

Your Answer

Accepted video resources