How to let try-catch works in LINQPad
Options
I'm trying to try-catch the folowing code in LINQPad. But LINQPad always stopped on Line 3. Can I just leave try-catch works as expected?
try { headers.GetValues("User-Agent"); } catch (IndexOutOfRangeException) { headers.Remove("User-Agent"); headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)"); }
Comments
-
What do you mean by "stopped"? Have you enabled "Break when exception is thrown" in the toolbar (the blue bug icon)? If so, uncheck that and it will run without breaking.
-
Yes, you are right. That's the point. Thank you!
-
Instead of using try/catch to check for existing values, which is considered bad practice (exceptions are costly), you better use
headers.AllKeys.Contains("User-Agent")
to check for an existing value.
But, a shorter path is redefining the header. Assuming Headers is of type WebHeaderCollection, use the this[string] or this[HttpRequestHeader] property (which you can examine using built-in ILSpy).
Using both named header "User-Agent" and enum HttpRequestHeader.UserAgent interchangeably:using (var client = new WebClient()) { client.Headers["User-Agent"] = "Test"; client.Headers.Dump(); client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)"; client.Headers.Dump(); }
More info on using exceptions for flow control: https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why -
This is actually a workaround due to a ASP.NET Core issue: https://github.com/dotnet/corefx/issues/34933
If the User-Agent malformed, any kind of read on that header will always throw exception! -
Oops, my bad, carry on