我正在使用一个简单的web客户端从web服务中检索一些XML,我将其封装在一个简单的try,catch块中(捕获WebException)。如下所示;
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://ip/services"));
}
catch (WebException e)
{
Debug.WriteLine(e.Message);
}否,如果我将IP地址更改为无效的IP地址,我会期望它抛出异常并将消息输出到调试窗口。但是它没有,似乎catch块甚至没有被执行。除以下内容外,不会显示任何内容和调试窗口;
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll我的代码在我看来是正确的,所以我不能理解为什么没有捕捉到异常?
发布于 2011-11-03 16:53:44
从您对错误消息的描述中,我假设实际抛出的异常是"FileNotFoundException“类型。
您是否尝试过捕获异常并检查类型?web异常可能是内部异常。
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://ip/services"));
}
catch (Exception ex)
{
Debug.WriteLine(ex.GetType().FullName);
Debug.WriteLine(ex.GetBaseException().ToString());
}更新:我刚刚注意到你实际调用的是一个异步方法。
作为一个健全的检查,我建议切换到非异步方法,并检查由此产生的错误。
WebClient.DownloadString Method (Uri)
您还可以从查看此页面中受益,该页面以web客户端为例介绍了如何捕获异步错误。
Async Exceptions
发布于 2011-11-03 17:49:19
异常永远不会从DownloadStringAsync中引发。它不会抛出它,但DownloadString (非异步)会抛出它。我不知道这是不是一个bug,我认为异步方法从来不会抛出除ArgumentException之外的异常,尽管文档states并非如此。
你必须“捕捉”DownloadStringCompletedEventHandler中的错误:
void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Debug.WriteLine(e.Error);
return;
}你几乎总是可以安全地忽略“先发制人”的异常,这些异常是在框架内捕获的,并相应地处理。有关这方面的更多信息,请参阅this question。
https://stackoverflow.com/questions/7991981
复制相似问题