使用webexception时出错

时间:2011-11-03 08:31:36

标签: c# windows-phone-7.1

我正在使用一个简单的webclient从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地址,我希望它抛出异常并将消息输出到调试窗口。但它没有,似乎捕获块甚至没有被执行。没有出现任何内容,调试窗口与以下内容不同;

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

我的代码看起来正确,所以我无法理解为什么没有捕获异常?

2 个答案:

答案 0 :(得分:7)

根据您对错误消息的描述,我假设抛出的实际异常是“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

答案 1 :(得分:3)

永远不会从DownloadStringAsync引发异常。它根本不会抛出它,但DownloadString(非异步)将抛出它。我不知道这是不是一个错误,我认为异步方法永远不会抛出除ArgumentException之外的异常,尽管文档states也是如此。

您必须“捕获”DownloadStringCompletedEventHandler中的错误:

void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        Debug.WriteLine(e.Error);
        return;
    }

您几乎总能安全地忽略“第一次机会”异常,这些异常会在框架内被捕获并相应地处理。有关详细信息,请参阅this question