使用WebException捕捉错误

6
我正在使用一个简单的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地址更改为无效的地址,我希望它会抛出异常并输出消息到调试窗口。但它没有,似乎连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

我的代码看起来没问题,我不明白为什么异常没有被捕获?


你尝试过捕获通用异常吗?例如 catch(Exception ex) - NaveenBhat
我使用异常得到了相同的结果。谢谢。 - Nathan
2个回答

8
根据您描述的错误消息,我认为实际抛出的异常类型是“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 方法(Uri)

您还可以从这个页面中受益,该页面通过使用 Web 客户端作为示例来遍历捕获异步错误。

异步异常


即使我在catch块中放置一个简单的Debug.WriteLine("test");,它仍然是一样的,它不会被执行,这表明catch块没有被执行。谢谢。 - Nathan
答案已更新,因为我注意到您正在调用异步方法。 - fluent
啊,谢谢!我不知道在异步操作时需要以不同的方式捕获异常。我没有使用您发布的方法(通过链接),而是在DownloadStringCompleted中检查错误,这很好用。感谢您让我找到答案! - Nathan

3

在DownloadStringAsync方法中,异常永远不会被抛出。它只是不会抛出异常,但是DownloadString(非异步)会抛出异常。我不知道这是否是一个bug,我认为异步方法除了ArgumentException外从不抛出异常,但是文档说明情况可能不同。

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

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

您几乎总是可以安全地忽略"first chance"异常,这些异常在框架内部被捕获并相应地处理。有关此内容的更多信息,请参见此问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接