Dam
Dam

Reputation: 41

What is the best, and cleanest way to close a file in Java inside a finally block

I wrote a method to close write to a file. However, a senior developer suggested me to close the file inside the finally block.

This is the method I have:

private static void writetoFiles(String error) {
    try {
        File file = new File("errorcode.txt");
        if (!file.exists()) {
            file.createNewFile();
    } else {
            FileWriter updateerrorcode = new FileWriter("errorcode.txt");
            updateerrorcode.write(error);
            updateerrorcode.close();
     }
    } catch (IOException e) {
    }
}

I read many answers in stackoverflow but all of them seemed a bit too complicated for a simple case like mine. Any suggestions how should I go about this?

Upvotes: 0

Views: 1246

Answers (2)

CryptoFool
CryptoFool

Reputation: 23139

Use a try-with-resource statement:

private static void writetoFiles(String error) {
    try {
        File file = new File("errorcode.txt");
        if (!file.exists()) {
            file.createNewFile();
        } else {
            try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
                updateerrorcode.write(error);
            }
        }
    } catch (IOException e) {
        // TODO: Handle error condition
    }
}

To point out a separate issue...I think your logic is wrong in your example. If the output file doesn't exist, all your code does is create the file. Only if the file already exists does it write the error text to it. I expect that you want to write the text in either case. If this is true, you don't need the createNewFile call at all, as the FileWriter class will create the file if it doesn't already exist. So I think what you really want is this:

private static void writetoFiles(String error) {
    try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
        updateerrorcode.write(error);
    } catch (IOException e) {
        // TODO: Handle error condition
    }
}

This will cause the writer to be properly closed in both the normal execution case and the error throw case. I assume that in your actual code, you'll do something with that IOException when it is caught. I can't know what you want to do there, so I won't propose anything.

If you want to strictly use a finally block, you can do this instead:

FileWriter updateerrorcode = new FileWriter("errorcode.txt");
try {
    updateerrorcode.write(error);
}
catch (IOException e) {
    // TODO: Handle error condition
}
finally {
    updateerrorcode.close();
}

This is the only option you would have had in earlier versions of Java, prior to the addition of the try-with-resource construct. In this second method, you might want to catch an error from close(), but in all of my 25+ years of experience with Java, I don't recall a close() call on a file failing. I guess you'd get that if you were out of disk space on your target volume and so close() couldn't flush the stream's write buffer. This issue is a distinct advantage of the newer method...failure to close the file won't affect the throw/catch of an exception thrown by the write() call.

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

The cleanest approach would be to do it using the try-with-resources statement as shown below:

private static void writetoFiles(String error) throws IOException {
    //...

    try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
        updateerrorcode.write(error);
    }

    //...
}

Do not catch an exception in a method if it can not handle it:

If the method, writetoFiles can not handle the exception, it should throw the same so that the calling method can handle it appropriately.

Upvotes: 3

Related Questions