Problem with “scopes” of variables in try catch blocks in Java

Because it’s declared in the try block. Local variables are declared in one block are inaccessible in other blocks except if contained in it, i.e., the variables go out of scope when their block ends. Do this:

private void loadCommands(String fileName) {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(fileName));

        while (br.ready()) {
            actionList.add(CommandFactory.GetCommandFromText(this, br.readLine()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) try { br.close(); } catch (IOException logOrIgnore) {}
    }       
}

Leave a Comment