Sonar violation: “Method may fail to close stream on exception”

前端 未结 4 1401
青春惊慌失措
青春惊慌失措 2021-01-28 00:15

I have this method:

 private void unZipElementsTo(String inputZipFileName, String destPath) throws FileNotFoundException, IOException {

        OutputStream out         


        
相关标签:
4条回答
  • 2021-01-28 00:36

    If out.close() or zf.close() in the finally block throw an exception then the other closes won't be executed.

    0 讨论(0)
  • 2021-01-28 00:43

    Alternatively if you're using Java 7 or better, you can use the new try-with-resources mechanism, which handles the close for you. See: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for details on this new mechanism.

    Note that try-with-resources also works with multiple objects that are opened and closed and still preserves the guarantee that objects will be closed in the reverse order of their construction. Quoth that same page:

    Note that the close methods of resources are called in the opposite order of their creation.

    0 讨论(0)
  • 2021-01-28 00:51

    That's right. The OutputStream.close() method can itself throw an exception. If this happens, e.g. on the 1st line of your finally{} block, then the other streams will be left open.

    0 讨论(0)
  • 2021-01-28 00:51

    To avoid masking an exception with an exception during the close of the streams It's often recommended to "hide" any io exception in the finally.

    To fix use the org.apache.commons.io.IOUtils.closeQuietly(...) or guava Closeables.html#closeQuietly(java.io.Closeable) in the finally close

    more on exception handling issues :
    http://mestachs.wordpress.com/2012/10/10/through-the-eyes-of-sonar-exception-handling/

    0 讨论(0)
提交回复
热议问题