Why is code in a try block separate from the rest of a method?

c#, exception

Solution

You're misunderstanding the error.

The `request` variable is in scope for all of the code. However, outside the `try` block, 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.Create` throws an exception, `request` will not have been assigned to.

You can fix it by assigning a value outside the `catch` block, like this:

HttpWebRequest request = null;

By the way, you should not be using a `catch` block at all here. Instead, you should call `Uri.TryCreate`.

Problem

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?

Original source