J
Jonathan Wood
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.
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? For that matter, how about
webRequest?
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?
try
{
// Get string to be posted
string post = PostString;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = PostString.Length;
using (StreamWriter writer = new
StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(post);
writer.Close();
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader reader = new
StreamReader(webResponse.GetResponseStream()))
{
_rawResult = reader.ReadToEnd();
reader.Close();
}
webResponse.Close();
}
catch (Exception e)
{
_message = e.Message;
}
Jonathan
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.
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? For that matter, how about
webRequest?
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?
try
{
// Get string to be posted
string post = PostString;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = PostString.Length;
using (StreamWriter writer = new
StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(post);
writer.Close();
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader reader = new
StreamReader(webResponse.GetResponseStream()))
{
_rawResult = reader.ReadToEnd();
reader.Close();
}
webResponse.Close();
}
catch (Exception e)
{
_message = e.Message;
}
Jonathan