error while using try with resources in Java

finally, java, try-catch-finally, try-with-resources

Solution

Taken from the Java Language Spec (14.20.3):

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block. catch clauses and a finally clause are often unnecessary when resources are closed automatically.

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

So you do not need to close the Resource anymore. Try-with-resources does it automatically for you and your `FileReader` will only be available in the `try` block. Thus you get that compile error.

Problem

I have this method where I am using try with resources of Java SE 7. ``` private void generateSecretWord(String filename){ try (FileReader files = new FileReader(filename)){ Scanner input = new Scanner(files); String line = input.nextLine(); String[] words = line.split(","); Collections.shuffle(Arrays.asList(words)); if (words[0].length()>1){ secretWord = words[0]; return; } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (files!=null) files.close(); } } ``` I get compile error in `finally` block that `files cannot be resolved to a variable` I have reference for files in the `try with block`. why do I get this error and how to fix it? Thanks

Original source