error while using try with resources in Java
Asked Answered
N

5

7

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

Neidaneidhardt answered 22/11, 2013 at 20:54 Comment(0)
S
6

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.

Shih answered 22/11, 2013 at 20:55 Comment(2)
does that mean a finally block is not needed or just closing files is not neededProboscis
@user2708477 It means that a finally block is not needed to close the Resources. If you need to do other things, which cannot be skipped even if an Exception happens, then you will still need a finally block. But if you just want to make sure that the files will be closed in any case, you don't need one, because that will be done implicitly.Shih
D
10

When you are using try with resources you don't need to explicitly close them. try-with-resources will take care of closing those resources.

Based on try-wtih-resource document

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

Delighted answered 22/11, 2013 at 20:55 Comment(0)
S
6

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.

Shih answered 22/11, 2013 at 20:55 Comment(2)
does that mean a finally block is not needed or just closing files is not neededProboscis
@user2708477 It means that a finally block is not needed to close the Resources. If you need to do other things, which cannot be skipped even if an Exception happens, then you will still need a finally block. But if you just want to make sure that the files will be closed in any case, you don't need one, because that will be done implicitly.Shih
E
2

Since no-one else has mentioned this, if you want to handle it manually you could do something like:

private void generateSecretWord(String filename){
        FileReader files = null;
        try {
            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(); 
        }

    }
Edh answered 22/11, 2013 at 21:5 Comment(0)
P
0

The code that you are trying to execute is old fashioned code before Java 7 where have to close the resources to avoid memory leaks. But in New Java 7 take it smartly and it is not necessary to close the resources even it is not accessible to finally block.

Petronel answered 24/8, 2018 at 5:5 Comment(0)
Y
0

in Pom.xml set java to 1.7 or higher as follows,

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <java.version>1.8</java.version>
</properties>
Yance answered 12/9, 2020 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.