Always close() in a finally block 45

Posted by Dean Wampler Thu, 31 Jul 2008 05:12:00 GMT

Here’s one for my fellow Java programmers, but it’s really generally applicable.

When you call close() on I/O streams, readers, writers, network sockets, database connections, etc., it’s easy to forgot the most appropriate idiom. I just spent a few hours fixing some examples of misuse in otherwise very good Java code.

What’s wrong the following code?

    
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(fileName);
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
    writer.write(content);
    writer.close();
}
    

It doesn’t look all that bad. It tells it’s story. It’s easy to understand.

However, it’s quite likely that you won’t get to the last line, which closes the writer, from time to time. File and network I/O errors are common. For example, what if you can’t actually write to the location specified by fileName? So, we have to be more defensive. We want to be sure we always clean up.

The correct idiom is to use a try … finally … block.

    
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(getFileSystemPath() + contentFilename);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
        writer.write(content);
    } finally {
        if (writer != null)
            writer.close();
    }
}
    

Now, no matter what happens, the writer will be closed, if it’s not null, even if writing the output was unsuccessful.

Note that we don’t necessarily need a catch block, because in this case we’re willing to let any Exceptions propagate up the stack (notice the throws clause). A lot of developers don’t realize that there are times when you need a try block, but not necessarily a catch block. This is one of those times.

So, anytime you need to clean up or otherwise release resources, use a finally block to ensure that the clean up happens, no matter what.

Comments

Leave a response

  1. Avatar
    Jaap Beetstra 26 minutes later:

    You should be careful with the constructor chaining here. If for some reason the OutputStreamWriter constructor throws an exception, the stream will nog be closed, since writer is not assigned yet. In this example it should not happen, but it would be possible if a different encoding is specified which is not necessarily available on the platform (iirc UTF-8 must be available according to the JLS).

    I usuallly use the idiom below, which has the same caveat, but is slightly more compact.
        
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
        try {
            writer.write(content);
        } finally {
            writer.close();
        }
    
  2. Avatar
    Andrew Rea about 9 hours later:

    In C# we also have a using statment block:

    using(FileStream fs1 = File.Open(@”C:\MyTricks.txt”)) { //...Bla Bla Bla }

    This automatically deals with the try, finally block in MSIL code. Nice shortcut and code/time saver in my opinion.

  3. Avatar
    Reader about 18 hours later:

    Jaap, how does your example code avoid the stream not being closed if OutputStreamWriter throws an exception? If it throws an exception the try block will never get executed and therefore the finally block will never get executed—you’re in the same situation as the original code.

  4. Avatar
    Reader about 18 hours later:

    You’ve still got a potentially unclosed stream if OutputStreamWriter throws. I think the following would cover that: FileOutputStream stream = null; try { stream = new FileOutputStream(output); writer = new OutputStreamWriter(stream, “UTF-8”); writer.write(content); } finally { if (writer != null) writer.close(); else if(stream != null) stream.close(); }

  5. Avatar
    JuanM about 19 hours later:

    This is one of the reasons why Closures would be useful for us Java Programmers, we could delegate the responsibility of closing the stream to the Stream, instead of closing it ourselves.

  6. Avatar
    Jaap Beetstra 1 day later:
    Jaap, how does your example code avoid the stream not being closed if OutputStreamWriter throws an exception?

    It doesn’t, it’s just somewhat more compact than the example in the posting.

    In the example given it is not really an issue anyway, since the constructor cannot fail (famous last words). If this a concern, such as with a different encoding, you could do it like this:
    OutputStreamWriter writer = null;
    OutputStream os= new FileOutputStream(output);
    try {
      // UTF-7 might not be available
      writer = new OutputStreamWriter(os, "UTF-7");
      writer.write(content);
    } finally {
      if (writer == null)
        os.close();
      else
        writer.close();
    }
    
  7. Avatar
    Dean Wampler 3 days later:

    I guess I blew the example a bit with the nested writer/stream creation. It shows how tricky this can be to implement robustly. Good comments, all.

    JuanM is right; a much better design would be for libraries with non-trivial recovery requirements to guarantee proper clean up, with a user specified closure or worker object to do the work on the open resources. Database Connections are another example where this design would be useful.

    When I’m designing an API, I try to ensure that there is no way the user can to use it incorrectly!

  8. Avatar
    Steve Freeman 5 days later:

    Jaap is right. The pattern should be

    Resource resource = makeResourceOrFail();
    try {
      doSomethingWith(resource);
    } finally {
      resource.close();
    }

    The only way to be really sure of all the corner cases is to insist on keeping things this clean. It’s not hard.

  9. Avatar
    Wmv to ipad about 1 year later:

    ah ha

  10. Avatar
    Convert DVD to HTC about 1 year later:

    ah ha ,it is really good! Here ,our PDF to BMP Converter will show you its main features and the easy-to use

    steps that how to convert PDF to BMP. With PDF to BMB Converter, you will find that it is very simple to convert PDF to BMP.also

    ,you can try hgfd

  11. Avatar
    Refugio Drews over 2 years later:

    I am happy to find a beautiful post for me. Now I am planing to extension cord

  12. Avatar
    fgf over 2 years later:

    ????“??”?? ?????????????20??80??????“??”??21???????????“?”?????VI???????????????????????????????????????

  13. Avatar
    bag factory over 2 years later:

    readers, writers, network sockets, database connections, etc., it’s easy to

  14. Avatar
    pandora bracelets over 2 years later:

    ` Avoid getting in a hurry to get a present for ones mom. Start searching ahead of time; waiting until the last second to find a found is often getting problems.Spending some time to learn what an individual’s Mum would like as well as might help guarantee that your gets the top found. If you opt for necklaces regarding Mom online will assist cut down the amount of time necessary to discover the proper jewelry pertaining to mama despite the fact that have waited through to the very end. Therefore when your going looking for mother’s day, on the liner where to begin from.

  15. Avatar
    oxpdffr over 2 years later:

    image en PDF convertisseur offre aux utilisateurs une solution facile pour convertir efficacement des images en fichiers PDF. Il passe par imprimante virtuelle installé dans votre ordinateur pour convertir des formats images( par exemple, JPG, JPEG, BMP,TIFF, etc) en PDF. Il y a plusieurs de méthodes de conversion que vous pouvez choisir préférée. Attention : Nous ne pouvons pas directement glisser/déplacer une image dans notre imprimante.

  16. Avatar
    iPhone contacts backup over 2 years later:

    This is the main function. I know that. It will run smoothly.

  17. Avatar
    Pandora over 2 years later:

    and he showed me a function he was writing. In the midst of the function I saw this

  18. Avatar
    DRM removal software over 2 years later:

    You know, to be a good programmer is not so easy. it is not to understand it, however, you can finish it, enjoy much. want to Know more about this topic.

  19. Avatar
    pandora over 2 years later:

    I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it!

  20. Avatar
    pandora over 2 years later:

    Had a pleasant answer virtually completed, had been substantiation reading the idea & acquired erased by an ad for Shipwreck beads. Been age ranges since I checked within below & left for the reason that major website modifications lsat summer season built contributing via dial-up Painful. I observe situations are much the same. Sleepless & jumped around from the Etsy community forums which in turn did not seize myself this evening… Spend time hiding about the boards & checking out items available for sale & not too long ago distributed. There ended up about 197,Thousand jewelry entries after i opened up our store (NGHDesigns) at the end of August. There are no longer Three hundred and fifty,Thousand now. I’ve had some accomplishment & take pleasure in taking part there, but am pleased that is not how we keep a ceiling more than each of our heads. Some sellers do very well right now there, other people certainly not offer anything. Even one of the most incredible goods are generally smothered

  21. Avatar
    Coach Factory Outlet over 2 years later:

    yes, but not very much. So I’m not going to be spending much

  22. Avatar
    http://www.blacktowhiteiphone4.com over 2 years later:

    Without switching lense on my 550D I couldn’t get any closer than this so the 100% crop below isn’t really accurate but it shows what kind of sharpness the white iPhone 4 is capable of. Impressive

  23. Avatar
    Criminal Check over 2 years later:

    @ Andrew Rea

    Thanks for giving a hint.

  24. Avatar
    Low Carb Snacks over 3 years later:

    et any Exceptions propagate up the stack (notice the throws clause). A lot of developers don’t realize that there are times when you need a try block, but not necessarily a catch block. This is one of those times.

  25. Avatar
    Criminal Records over 3 years later:

    A lot of developers don’t realize that there are times when you need a try block, but not necessarily a catch block. This is one of those times.

  26. Avatar
    Ray Ban over 3 years later:

    Finally it has been explained, thank you

  27. Avatar
    ralph lauren over 3 years later:

    Easily alter the brightness 80-fuschia pink vibe, the ghd striking styler arrives with three pink lip high shine ghd to complement every solitary mood, Dare, Dazzle and good for design and high shine in a fellow or young lady splendid package.

  28. Avatar
    okey oyunu oyna over 3 years later:

    very good for your explanation.

    internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.

  29. Avatar
    canada goose jackets over 3 years later:

    I loved this chapter. I can’t wait for the next one.

  30. Avatar
    christian louboutin shoes on sale over 3 years later:

    Have the christian louboutin patent leather pumps is a happy thing. Here have the most complete kinds of christian louboutin leather platform pumps.

  31. Avatar
    Bowtrol over 3 years later:

    hmm ,i’m not sure if this is what i’m looking for but anyway this is interresting and could be useful some day,thanks for taking time to write such cool stuff

  32. Avatar
    beats by dr dre over 3 years later:

    ’m looking for but anyway this is interresting and could be useful some day,thanks for tabeats by dr dre beats by dre saleking time to write such cool stuff

  33. Avatar
    Diablo3 over 3 years later:

    it needs a bokmark so i can come back to it later ,nice stuff

  34. Avatar
    canada goose coat over 3 years later:

    When it comes to feather dress, what appears in your mind? Which kind brand of down jacket do you like prefer? Though there are many down jackets for you to choose from, on the word, which one you really enjoy? I want to say that canada goose coats is really your best choice. I believe you can’t agree with me any more. When you take the quality into consideration, you will find that it is superior to any other kind of coat. Besides, discount canada goose jackets is a world well-known brand, which has gained high reputation in the world, which has accepted by our customers and some organization. Because of its high quality, some of our loyal customers have promoted it to the people around them. In their opinion, it is good to informing others to know it. Recently, Canada Goose Trillium Parka is on hot sale. What I have to inform you is that all the products there are made by hand, so they are elaborative and elegant enough. It is really beautiful once you dress in. So, if you are a lovely girl or woman, go to the store to buy one for you. You will appreciate it that you have such a coat.In addition, they also have any other products like canada goose Gloves and canada goose jacket supplier.Hope your will like its!

  35. Avatar
    ferragamo shoes over 3 years later:

    Ferragmo belt from ferragamo outlet has top quality with best craftsmanship. Now Salvatore ferragamo sale belts online with reasonable price and free shipping.

  36. Avatar
    discount oakley fives sunglasses over 3 years later:
  37. Avatar
    Fake Oakley Gascan sunglasses over 3 years later:
  38. Avatar
    Fake Oakley Radar over 3 years later:
  39. Avatar
    Fake Oakley Polarized Sunglasses over 3 years later:
  40. Avatar
    ysbearing over 3 years later:

    Slewing ring is also called slewing bearing, some people called: rotary support, swing support. English Name: slewing bearing or slewing ring bearing or turn table bearing, slewing ring in the real industrial applications is very wide.

  41. Avatar
    Tips For Bowling over 3 years later:

    And, moreover, it is art in its most general and comprehensive form that is here discussed, for the dialogue embraces everything connected with it, from its greatest object, the state, to its least, the embellishment of sensuous existence.

  42. Avatar
    christian louboutin over 3 years later:

    The professional design make you foot more comfortable. Even more tantalizing,this pattern make your legs look as long as you can,it will make you looked more attractive.Moveover,it has reasonable price.If you are a popular woman,do not miss it.

    Technical details of Christian Louboutin Velours Scrunch Suede Boots Coffee:

    Color: Coffee
    Material: Suede
    4(100mm) heel
    Signature red sole x

    Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Tall Boots, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.

  43. Avatar
    koko over 3 years later:

    oakley mens antix sunglassesoakley batwolf sunglassesdiscount oakley batwolf sunglassesoakley batwolf sunglasses saleoakley mens batwolf sunglassesoakley dispatch sunglassesdiscount oakley dispatch sunglassesoakley dispatch sunglasses saleoakley mens dispatch sunglassesoakley fives squared sunglassesdiscount oakley fives squared sunglassesoakley fives squared sunglasses saleoakley mens fives squared sunglassesoakley fuel cell sunglassesdiscount oakley fuel cell sunglassesoakley fuel cell sunglasses saleoakley mens fuel cell sunglassesoakley gascan sunglassesdiscount oakley gascan sunglassesoakley gascan sunglasses saleoakley mens gascan sunglassesoakley half wire sunglassesdiscount oakley half wire sunglassesoakley half wire sunglasses saleoakley mens half wire sunglassesoakley hijinx sunglassesdiscount oakley hijinx sunglassesoakley hijinx sunglasses sale

  44. Avatar
    tv show over 3 years later:

    good stuff. thanks for posting it!

  45. Avatar
    ralph lauren over 4 years later:

    Siècle Série classique américain de los angeles marque Ralph Lauren hommes d’hiver communiqué de 2012, los angeles principale saison des longues de design guy cuir, créateurs intelligents ajouté fermeture éclair dans los angeles couche moyenne de cuir, veste durante cuir cuando longtemps devient instantanément courtroom. Los angeles couleur beige et noir également, put créer united nations design parfait guy scandinaves.http://www.vetementpoloralphlauren2012.net

Comments