tags:

views:

177

answers:

2

Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause, setting it as final, etc. Does this have anything to do with Java not support closures? I am 99% confident similar code would work in C#.

private void loadCommands(String fileName) {
    try {
        final BufferedReader 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) br.close(); //<-- This gives error. It doesn't
                                    // know the br variable.
    }       
}

Thanks

A: 

br is defined in the try block so it's not in the scope in finally block.

Define br outside of the try block.

ZZ Coder
+11  A: 

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) {}
    }       
}
Artefacto
I waas almost sure I tried that same code here and it didn't work. Well, thanks!
devoured elysium
ok, great. Now it won't let me do the br.close() without surrounding it in another try catch block. What am I supposed to do?
devoured elysium
Just put that another try/catch block in ;)
BalusC
:), sometimes, Java code is verbose, be familiar with that
vodkhang
I dunno if I'd say verbose or irritating.
devoured elysium
That's why under each [IOUtils](http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) exist.
BalusC
Maybe you, devoured elysium, omitted the ` = null;` which is hard to accept, because when you omit it, you get the message 'br might be null/ not be initialized', which means, it is null, but if you write it explicitly, it is silently accepted. Too nanny-like, but well meant, imho.
user unknown