0

I am using try with resources, and I found if I use the out statement, then I get something wrong

Correct one,

try (FileWriter fstream = new FileWriter(mergedFile, true);) { } 

Incorrect one

FileWriter fstream = null; try (fstream = new FileWriter(mergedFile, true);) { } 

I am wondering why I cannot use the second one? The scope of with resources is different?

3
  • Resources in a try-with-resources block only exist inside it and are closed automatically when the block is left. Commented May 23, 2017 at 7:19
  • Try catch block limits the scope Commented May 23, 2017 at 7:20
  • Because variable is out of scope to try with resources that needs to be closed at the end. Commented May 23, 2017 at 7:21

2 Answers 2

1

Yes, that's correct, since a resource declared with try with resources is closed at the end of the block, it is not available outside the scope of that block.

Having a resource persist in the scope after the block wouldn't make sense, since it's already closed and you most probably can't make use of it (some sort of "reset" nonwithstanding).

You can also re-use the same variable name in multiple blocks, since it only exists in the block's scope.

So you could follow with another try (FileWriter fstream = ...) after your first block.

Sign up to request clarification or add additional context in comments.

Comments

0

There are two reasons , 1. Resource has to be final. outside declared variable may be changed at any point during the execution of the try-with-resources block. This would break its cleanup and will make it inconsistant.

  1. Resource scope must be try block associate with it.

Following are the exact words from Java 7 Specification Document,

A ResourceSpecification declares one or more local variables with initializer expressions to act as resources for the try statement.

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.

Also from 6.3 of Specification

The scope of a variable declared in the ResourceSpecification of a try-with-resources statement (§14.20.3) is from the declaration rightward over the remainder of the ResourceSpecification and the entire try block associated with the try-with-resources statement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.