Re: Problems Handling Errors Correctly
- From: Peter Duniho <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Sat, 15 Sep 2007 11:07:45 -0700
Jonathan Wood wrote:
I'm trying to figure out the best way to handle errors in my code.
I understand try...catch...finally just fine. But I find that in practice (in large part due to the lack of deterministic finalization), it's rarely that simple.
Actually, it is simple.
Consider the following code. In order to ensure my writer and reader object clean up in a timely manner no matter what, I've added two using blocks. But do I need another using block for webResponse?
You need webResponse to be in a using block, yes. But note that since the "using() { }" block itself qualifies as a statement, you can simply put two using statements with each other:
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
// code here
}
If you prefer, you could do this instead, which is equivalent to the above:
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(),
StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
// code here
}
It need not be messy.
For that matter, how about webRequest?
No.
This is what has always bothered me about .NET. Doesn't using add it's own try...catch...finally blocks? In the end, it's really not clear where I need them and where I don't, so I end up with tons of them. And that can't be good for performance. Any suggestions?
Yes. If the class implements IDisposable, then you need the "using" statement. If it doesn't, you don't.
Pete
.
- Follow-Ups:
- Re: Problems Handling Errors Correctly
- From: Jonathan Wood
- Re: Problems Handling Errors Correctly
- References:
- Problems Handling Errors Correctly
- From: Jonathan Wood
- Problems Handling Errors Correctly
- Prev by Date: Re: is there some per-process-limit on memory in .net processes?
- Next by Date: Re: Uniquely Identifying Multiple/Concurrent Async Tasks
- Previous by thread: Problems Handling Errors Correctly
- Next by thread: Re: Problems Handling Errors Correctly
- Index(es):
Relevant Pages
|