【问题标题】:Error catching with webexception使用 webexception 捕获错误
【发布时间】:2015-07-02 18:10:20
【问题描述】:

我正在使用一个简单的 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)
  • 我使用异常得到了同样的结果。谢谢

标签: c# windows-phone-7.1


【解决方案1】:

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

【讨论】:

  • 还是一样,即使我放了一个简单的 Debug.WriteLine("test");在 catch 块中它没有被执行,这表明 catch 块没有被执行。谢谢
  • 答案已更新,因为我注意到您正在调用异步方法
  • 啊谢谢!我不知道你在做异步事情时必须以不同的方式捕获异常。我没有使用您发布的方法(通过链接),而是检查了运行良好的 DownloadStringCompleted 中的错误。感谢您让我回答!
【解决方案2】:

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

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

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

您几乎总是可以安全地忽略“第一次机会”异常,这些异常会在框架内捕获并进行相应处理。有关更多信息,请参阅this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2018-03-25
    相关资源
    最近更新 更多