How to let try-catch works in LINQPad

edited January 30
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?

catch (IndexOutOfRangeException)
    headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)");


  • 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! :smile:
  • edited January 30
    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[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)";

    More info on using exceptions for flow control:
  • This is actually a workaround due to a ASP.NET Core issue:

    If the User-Agent malformed, any kind of read on that header will always throw exception!
  • Oops, my bad, carry on :)
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!