Reputation: 4992
I have the following code:
try {
reader = new BufferedReader(new FileReader(file));
String records = "";
System.out.println("EMITTER QUEUE BACKUP: restoring from file...");
try {
while(reader.ready()) {
records += reader.readLine();
}
} catch (IOException e) {
System.out.println("EMITTER QUEUE BACKUP: error restoring");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
doSomethingWith(records);
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The records
variable in the doSomethingWith(records);
line causes an error as undefined. This is ok, I can understand that its definition in the first try
block sometimes may not occure. But there is the question: if I delete the doSomethingWith(records);
line then the records
variable in the first try
block is marked as unused!!! So why does it recognize it as used in that line even if it causes an apparent mistake because it is assumed that it is not the same variable and thus it can't stand for a usage case of the String records = ""
?
If that matters, my IDE is Eclipse.
Upvotes: 1
Views: 1424
Reputation: 13872
{
and }
decide the scope for a construct in Java.
records
variable scope is limited to the end brace to try
construct and you are trying to use it outside, i.e. within finally
block. and that's why you are getting error.
line causes an error as undefined. This is ok, I can understand that its definition in the first try block sometimes may not occure.
Actually that's not the reason. but it's realated to the scope of variable.
if I delete the doSomethingWith(records); line then the records variable in the first try block is marked as unused!!!
Assigning a variable is not considered by Java that it is being used.
And error is preferred over warning.
Upvotes: 1
Reputation: 183
You can initialize records before the start of try i suppose because as it is you are making it an empty string. ""
Upvotes: -1
Reputation: 637
records
is assigned inside "try" block but is never read. Assigning a variable without reading the result is useless.
Upvotes: 0
Reputation: 6532
It's not just that the definition may not occur, the variable declaration is outside the scope of the finally block. If that's declared outside the try it will stop the error.
As to why eclipse doesn't state that it's unused when the error is present, my guess is that the error is obscuring the warning? It never gets to the warning stage as the error occurs first in the compilation process?
Upvotes: 2