Search code examples
c#.netwebclient

Exception handling the right way for WebClient.DownloadString


I was wondering what exceptions I should protect myself against when using WebClient.DownloadString.

Here's how I'm currently using it, but I'm sure you guys can suggest better more robust exception handling.

For example, off the top of my head:

  • No internet connection.
  • Server returned a 404.
  • Server timed out.

What is the preferred way to handle these cases and throw the exception to the UI?

public IEnumerable<Game> FindUpcomingGamesByPlatform(string platform)
{
    string html;
    using (WebClient client = new WebClient())
    {
        try
        {
            html = client.DownloadString(GetPlatformUrl(platform));
        }
        catch (WebException e)
        {
            //How do I capture this from the UI to show the error in a message box?
            throw e;
        }
    }

    string relevantHtml = "<tr>" + GetHtmlFromThisYear(html);
    string[] separator = new string[] { "<tr>" };
    string[] individualGamesHtml = relevantHtml.Split(separator, StringSplitOptions.None);

    return ParseGames(individualGamesHtml);           
}

Solution

  • If you catch WebException, it should handle most cases. WebClient and HttpWebRequest throw a WebException for all HTTP protocol errors (4xx and 5xx), and also for network level errors (disconnection, host not reachable, etc)


    How do I capture this from the UI to show the error in a message box?

    I'm not sure I understand your question... Can't you just show the exception message?

    MessageBox.Show(e.Message);
    

    Don't catch the exception in FindUpcomingGamesByPlatform, let it bubble up to the calling method, catch it there and show the message...