Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is closing resources in try block accepted?

Tags:

java

exception

io

A beginners book on Java has the following code in it. This book also explains about exceptions very well, and since I understood how exception works, I got a question about the following code.

For some reason if FileWriter class throws an exception, writer.close() wouldn't be executed. Therefore I think the best place to close the writer object is in a finally block. Even prior to this I have seen many code written like this, where the resource will be closed in the try block itself. I think there is no point in doing so. Only when there is no exception the resource will be closed.

Am I wrong? What is the best way to close resources in java. Should we never write code like the following?

 public static void main(String[] args) {

       try{
         FileWriter writer = new FileWriter("file.txt");
         writer.write("i am writing");
         writer.close();
       }catch(IOException e){
           ex.printStackTrace();
       }

    }
like image 709
DesirePRG Avatar asked Dec 20 '22 05:12

DesirePRG


1 Answers

I agree with @cyber-rookie, it is probably best to close resources in a finally block.

Java 7 introduced "try-with-resources" in order to cut down on programming mistakes...

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

You can now write...

    try (FileWriter writer = new FileWriter("file.txt")) {
        writer.write("i am writing");
    } catch (IOException e) {
        e.printStackTrace();
    }

The compiler will add the extra code to close the writer at the end of the block for you

like image 167
BretC Avatar answered Dec 26 '22 00:12

BretC