Article View: comp.lang.java.programmer
Article #162Re: Problems with blocking socket
From: Timo Kinnunen
Date: Mon, 11 Feb 2002 15:45
Date: Mon, 11 Feb 2002 15:45
56 lines
2513 bytes
2513 bytes
Jon Skeet <skeet@pobox.com> wrote:
> Rosinger <rosinger@optushome.com.au> wrote:
>> System.out.println (response);
>>
>> in.close();
>> out.close();
>> socket.close();
>> }
>> }
>
> These close calls should be part of a finally block, so they get
> executed even if an IO exception is thrown.
What is the best way to close multiple streams? This ofcourse depends
on whether the method has been declared to throw an IOException. I've
considered a lot of different approaches, but I haven't found a winner
yet. Some of the better:
Doesn't throw an IOException:
try {
// ...
} finally {
closeIfNonNullAndIgnoreIOException(in);
closeIfNonNullAndIgnoreIOException(out);
closeIfNonNullAndIgnoreIOException(socket);
}
Throws an IOException:
try {
// ...
} catch(IOException e) {
closeIfNonNullAndIgnoreIOException(in);
in = null;
closeIfNonNullAndIgnoreIOException(out);
out = null;
closeIfNonNullAndIgnoreIOException(socket);
socket = null;
throw e;
} finally {
try {
if(in != null) in.close();
} finally {
try {
if(out != null) out.close();
} finally {
if(socket != null) socket.close();
}
}
}
--
No address munging in use. I like the smell of nuked accounts in the
morning.
Technical Details
Message-ID:
<Xns91B2B43D4BB72timokinnunenbigfootc@127.0.0.1>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!newsfeed.stanford.edu!logbridge.uoregon.edu!news.maxwell.syr.edu!newsfeed.online.be!ams.uu.net!newsfeed.song.fi!news.cs.hut.fi!not-for-mailReferences:
<3C67B406.1070407@optushome.com.au> <MPG.16d1cd1ffbee75e098aa59@dnews.peramon.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 10a146,610ca5e9d6f87bb8 X-Google-Attributes: gid10a146,public X-Google-Thread: 10d6db,610ca5e9d6f87bb8 X-Google-Attributes: gid10d6db,public X-Google-ArrivalTime: 2002-02-11 07:43:05 PST Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!newsfeed.stanford.edu!logbridge.uoregon.edu!news.maxwell.syr.edu!newsfeed.online.be!ams.uu.net!newsfeed.song.fi!news.cs.hut.fi!not-for-mail From: Timo Kinnunen <timo.kinnunen@bigfoot.com> Newsgroups: comp.lang.java.programmer,aus.computers.java Subject: Re: Problems with blocking socket Date: 11 Feb 2002 15:45:24 GMT Organization: My Organization Lines: 56 Message-ID: <Xns91B2B43D4BB72timokinnunenbigfootc@127.0.0.1> References: <3C67B406.1070407@optushome.com.au> <MPG.16d1cd1ffbee75e098aa59@dnews.peramon.com> NNTP-Posting-Host: kosh.hut.fi X-Trace: midnight.cs.hut.fi 1013442324 11763 255.255.255.255 (11 Feb 2002 15:45:24 GMT) X-Complaints-To: abuse@niksula.cs.hut.fi NNTP-Posting-Date: 11 Feb 2002 15:45:24 GMT User-Agent: Xnews/4.06.22