Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error while using try with resources in Java

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

like image 803
brain storm Avatar asked Nov 22 '13 20:11

brain storm


People also ask

What happens if try-with-resources throws an exception?

For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.

How try-with-resources work in Java?

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.

Can we use try-with-resources without catch and finally?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.


3 Answers

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.

like image 164
kosa Avatar answered Sep 21 '22 12:09

kosa


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.

like image 32
noone Avatar answered Sep 22 '22 12:09

noone


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(); 
        }

    }
like image 35
Michael Carver Avatar answered Sep 19 '22 12:09

Michael Carver