Skip to content
ExamSpine

Answer it

Handling a missing class list file

5 marksYou mark it yourself against the marking points

A teacher's attendance app loads a class list, one name per line, with this function. Here is the program.

def load_names(path):
    names = []
    try:
        with open(path, "r") as f:
            for line in f:
                names.append(line.strip())
    except FileNotFoundError:
        print("No class list found: " + path)
    return names
static ArrayList<String> loadNames(String path) {
    ArrayList<String> names = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        String line = reader.readLine();
        while (line != null) {
            names.add(line.strip());
            line = reader.readLine();
        }
    } catch (FileNotFoundException e) {
        System.out.println("No class list found: " + path);
    } catch (IOException e) {
        System.out.println("Could not read: " + path);
    }
    return names;
}

(a) The teacher asks for class_11b.txt, which does not exist. State what the function prints and what it returns. [2]

(b) Explain why catching this error is better for the teacher than letting the program stop. [2]

(c) Identify one other problem, apart from a missing file, that can stop a program opening a file for reading. [1]

[5]

Report a problem with this page