Java. What is the valid way try to close all connections? [duplicate]

夙愿已清 提交于 2019-12-22 10:54:14

问题


For example, I have method for working with input/output streams:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
try{                     
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections
        out1.close();
        out2.close();
        in1.close();
        in2.close();
        }    
            }

Method can throws IOException and it is valid behavior. But If I have Exception in this line:

 out1.close();

others three Stream will be NOT closed. What solution can you recommend? How? How close all?

I have just one:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
         try{            
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections

try{out1.close();}
  finally{
     try{out2.close();}
         finally{
            try{in1.close();}
                finally{
        in2.close();}
}}

}

            }

As you can see - my approach is using multiple try-finally blocks.

Do you think it is good idea?


回答1:


If three streams are not dependent on each other, may be having try/catch for each stream look cleaner.

Something like:

try{
 out1.close();
}catch(Exception e)
{
....
}finally

{.... }

try{
        out2.close();
}catch(Exception e)
{
.....
}finally

{.... }

EDIT: As iccthedral suggested, if you use Java7 you may use try-with-resource block.




回答2:


Probably the best way to go about it is:

try (
     OutputStream out1 = ...;
     OutputStream out2 = ...;
     InputStream in1 = ...;
     InputStream in2 = ...;
) {
     ...
}



回答3:


Perhaps the best way to clean this up is to make a method like this:

public static void close(Closeable c) {
   if (c == null) return; 
   try {
       c.close();
   } catch (IOException e) {
       // Do anything or nothing
   }
}

This can replace your .close() calls and won't throw exceptions if they fail.



来源:https://stackoverflow.com/questions/12372879/java-what-is-the-valid-way-try-to-close-all-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!