Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 863
user471011 Avatar asked Dec 06 '25 08:12

user471011


2 Answers

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.

like image 79
kosa Avatar answered Dec 07 '25 21:12

kosa


Probably the best way to go about it is:

try (
     OutputStream out1 = ...;
     OutputStream out2 = ...;
     InputStream in1 = ...;
     InputStream in2 = ...;
) {
     ...
}
like image 25
Tom Hawtin - tackline Avatar answered Dec 07 '25 22:12

Tom Hawtin - tackline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!