Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Exception Handling

Status
Not open for further replies.

daint

Technical User
Oct 4, 2000
46
0
0
GB
Hello all,

I'm still learning a lot with C#, and now come across a seamingly easy question, but can't seem to find the answer.

I'm trying to write a simpke class to send a web request and return the reply. This works, but the error handling doesn't.

I'm trying to figure out whether the server is down, whether the requested file is missing, if there is a problem with the requested file, and possibly if the wireless network (which the device is using) is currently no on the network.

So far my code looks a little like this:

public string webSend(string postData, string page)
{
string website = " + activeServer + "/" + activeFolder + page;
string reply = "";

try
{
WebRequest myWebRequest = WebRequest.Create(website);

myWebRequest.Method = "POST";

myWebRequest.Timeout = 10000;
myWebRequest.ContentType = "application/x-
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

myWebRequest.ContentLength = byteArray.Length;

using (Stream datastream = myWebRequest.GetRequestStream())
{
datastream.Write(byteArray, 0, byteArray.Length);
}

WebResponse resp = myWebRequest.GetResponse();
StreamReader strm = new StreamReader(resp.GetResponseStream());

reply = strm.ReadToEnd();

strm.Close();
resp.Close();
}
catch (Exception ex)
{
MessageBox.Show("website : " + website);
MessageBox.Show("postData : " + postData);
MessageBox.Show("Webrequest : " + ex.ToString());
}
return reply;
}

As you can probably see, a pretty simply procedure, but currently can't distinguish between errors, etc...

Any ideas?

Thanks

Daint
 
As you can probably see, a pretty simply procedure, but currently can't distinguish between errors, etc..."

Do you mean that you want to handle certain errors differently? If so then add some more specific catch blocks before the generic one that you used, or in your catch block do certain things for certain error types (like if (ex.type) == 'system.sqlexception').

Not sure if this is the answer to your question or not.
 
let the compiler do the type checking, use:

Code:
try
{
 // code that throws an error
}
// e.g.
catch ( ArgumentOutOfRangeException aex )
{
 // deal with ArgumentOutOfRangeException
}
// e.g.
catch ( SomeOtherException soex )
{
}
catch ( Exception ex )
{
 // you really shouldn't ever get one of these
}
finally
{
 // just to be sure
}


mr s. <;)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top