Re: Problems Handling Errors Correctly



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
.



Relevant Pages

  • Re: Problems Handling Errors Correctly
    ... I do recall how hard the .NET developers tried to find a ... solution to the lack of deterministic finalization, ... StreamReader reader = new ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Problems Handling Errors Correctly
    ... Well now, I do recall how hard the .NET developers tried to find a solution to the lack of deterministic finalization, so I don't quite agree that "it is simple" tells the entire story. ... using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse) ... using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) ...
    (microsoft.public.dotnet.languages.csharp)