Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with "scopes" of variables in try catch blocks in Java

Tags:

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

like image 376
devoured elysium Avatar asked May 18 '10 01:05

devoured elysium


People also ask

Can you access variables from TRY in catch?

So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Which errors Cannot be handled by catch block?

The only exception that cannot be caught directly is (a framework thrown) StackOverflowException. This makes sense, logically, as you don't have the space in the stack to handle the exception at that point.

What happens if we place return statement in try catch block?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned.

What happens if error occurs in try block?

If any statement within the try -block (or in a function called from within the try -block) throws an exception, control is immediately shifted to the catch -block. If no exception is thrown in the try -block, the catch -block is skipped.


1 Answers

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) {}     }        } 
like image 108
Artefacto Avatar answered Oct 26 '22 14:10

Artefacto