user1883212
user1883212

Reputation: 7859

try-with-resources or close() dilemma

I have a function that can throw IOException, so I don't catch the exception internally. however I've some resources to close. Is it correct to do in that way, using try-with-resource (without any catch block):

public void workOnFiles() throws IOException {

    try(FileInputStream fis = new FileInputStream("bau.txt");) {
        // Do some stuff
    }       
}

Or I should do something like that:

public void workOnFiles() throws IOException {

    FileInputStream fis = new FileInputStream("bau.txt");
    // Do some stuff
    fis.close();    
}

Upvotes: 1

Views: 137

Answers (3)

Prabhaker A
Prabhaker A

Reputation: 8473

try-with-resources always closes(Closeable resources) the resource whether exception raises or not(Work only java7 onwards).

Where as your second code do not close resource if exception raises.
So you can use try-with-resources if you are using java7 or else edit your code with try and finally block.

finally block guarantees execution irrespective of exception raises or not

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213281

In 2nd one, if the exception is thrown, your fis won't be closed. An option is to enclose the statement that can throw th exception in a try block, and close the fis in a finally block.

But, since you are already on Java 7, you should use try-with-resource.

Upvotes: 5

AllTooSir
AllTooSir

Reputation: 49382

If you are keen on using the second method , then close the resource in finally block.

public void workOnFiles() throws IOException {
   FileInputStream fis = null;
   try {
     fis = new FileInputStream("bau.txt");
   // Do some stuff
   }
   finally  {
     try {
      fis.close(); 
     }
     catch(Exception e) {
      //logger.error(e);
      // e.printStackTrace();
     }   
}

Upvotes: 0

Related Questions