Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try...catch inside finally when releasing resource?

Tags:

I want to write a String to a Unicode file. My code in Java is:

public static boolean saveStringToFile(String fileName, String text) {
    BufferedWriter out = null;
    boolean result = true;
    try {
        File f = new File(fileName);
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(f), "UTF-8"));
        out.write(text);
        out.flush();
    } catch (Exception ex) {
        result = false;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
                // nothing to do! couldn't close
            }
    }

    return result;
}

Update

Now compare it to C#:

    private static bool SaveStringToFile(string fileName, string text)
    {
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            writer.Write(text);
        }
    }

or even try..catch form would be:

    private static bool SaveStringToFile(string fileName, string text)
    {
        StreamWriter writer = new StreamWriter(fileName);
        try
        {
            writer.Write(text);
        }catch (Exception ex)
        {
            return false;
        }
        finally
        {
            if (writer != null)
                writer.Dispose();
        }
    }

Maybe it's because I'm from the C# and .Net world. But is this the right way to write a String to a file? It's just too much code for such simple task. In C#, I would say to just out.close(); and that was it but it seems a bit strange to add a try..catch inside a finally statement. I added the finally statement to close the file (resource) no matter what happens. To avoid using too much resource. Is this the right way in Java? If so, why close throws exception?

like image 221
Alireza Noori Avatar asked Jan 04 '13 11:01

Alireza Noori


People also ask

Can we place try catch blocks inside finally?

A try-finally block is possible without catch block. Which means a try block can be used with finally without having a catch block.

Can you put a try catch in a finally?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Does finally run after try catch?

The finally-block The finally block contains statements to execute after the try block and catch block(s) execute, but before the statements following the try... catch... finally block.


2 Answers

You are correct in that you need to call the close() in the finally block and you also need to wrap this is a try/catch

Generally you will write a utility method in you project or use a utility method from a library like http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable) to closeQuietly .i.e. ignore any throw exception from the close().

On an additional note Java 7 has added support for try with resources which removes the need to manually close the resouce - http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

like image 50
bstick12 Avatar answered Dec 20 '22 07:12

bstick12


Yes, There is nothing strange about Try catch inside finally() in java. close() may throw IoException for various reasons, thats why it has to enclosed by try catch blocks. There is an improved solution to this problem of yours, in the latest java SE 7 Try with resources

like image 44
codeMan Avatar answered Dec 20 '22 09:12

codeMan