2011-11-03 148 views
3

我正在使用一個簡單的Web客戶端從Web服務檢索一些XML,我有這個封裝在一個簡單的嘗試,catch塊(捕捉WebException)。如下所示;錯誤捕捉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 

我的代碼看起來很對我,所以我不明白爲什麼異常不被捕獲?

+0

您是否試圖捕獲一般異常?像catch(Exception ex)' – NaveenBhat

+0

我使用異常獲得相同的結果。謝謝 – Nathan

回答

5

從您對錯誤消息的描述中,我會假設拋出的實際異常是類型「FileNotFoundException」。

您是否嘗試過捕獲異常並檢查類型?這可能是網絡異常是內部異常。

 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

+0

仍然一樣,即使我把一個簡單的Debug.WriteLine(「測試」);在catch塊中它不會被執行,這表明catch塊沒有被執行。謝謝 – Nathan

+0

回答更新,因爲我注意到你正在調用一個異步方法 – fluent

+0

啊謝謝你!我不知道你在做異步事情時必須以不同的方式捕獲異常。我沒有使用你發佈的方法(通過鏈接),而是檢查了DownloadStringCompleted中的錯誤,這很好。感謝您讓我接受答案! – Nathan

3

例外絕不會從DownloadStringAsync提高。它根本不會拋出它,但DownloadString(非Async)會拋出它。我不知道這是否是一個錯誤,我認爲異步方法不會拋出異常除了ArgumentException外,儘管文檔states其他。

你要「抓」在DownloadStringCompletedEventHandler錯誤:

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

幾乎總是可以忽略「第一次機會」的異常,這些都是框架內捕獲並做相應的處理。有關更多信息,請參閱this question