My problem goes something like this:
HttpWebRequest request;
try {
request = (HttpWebRequest) WebRequest.Create(url);
} catch (UriFormatException) {
statusLabel.Text = "The address you entered was malformed, please correct it.";
statusLabel.ForeColor = Color.Red;
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
The error I’ll get from this is that request hasn’t been given a value. Obviously this is because the value for request is given in the try block.
The reason this confuses me is because in other languages I’ve used, code in a try block isn’t kept separate (I forget the word for this, possibly encapsulation?) from the rest of the code – similar to a method.
Am I going about this the wrong way? Should I duplicate the code in the try block after the exception supposing WebRequest doesn’t throw one?
You’re misunderstanding the error.
The
requestvariable is in scope for all of the code. However, outside thetryblock, it is not guaranteed to have a value, and the C# compiler will not allow you to use a variable unless it can be sure that the variable has already been assigned.Specifically, if
WebRequest.Createthrows an exception,requestwill not have been assigned to.You can fix it by assigning a value outside the
catchblock, like this:By the way, you should not be using a
catchblock at all here.Instead, you should call
Uri.TryCreate.