【发布时间】:2011-08-25 08:20:04
【问题描述】:
我想知道在使用 WebClient.DownloadString 时我应该保护自己免受哪些例外的影响。
这是我目前使用它的方式,但我相信你们可以建议更好更健壮的异常处理。
例如,在我的脑海中:
- 没有互联网连接。
- 服务器返回 404。
- 服务器超时。
处理这些情况并向 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);
}
【问题讨论】: