2012-02-26 25 views
1

我有以下代碼:引發WebException被逮住

try 
{ 
    using (var myHttpWebResponse = (HttpWebResponse) httPrequestCreated.GetResponse()) 
    { 
     var streamResponse = myHttpWebResponse.GetResponseStream(); 

     if (streamResponse != null) 
     { 
      var streamRead = new StreamReader(streamResponse); 
      var readBuff = new Char[256]; 
      var count = streamRead.Read(readBuff, 0, 256);   

      while (count > 0) 
      { 
       var outputData = new String(readBuff, 0, count); 
       finalResopnse += outputData; 
       count = streamRead.Read(readBuff, 0, 256); 
      } 
      streamRead.Close(); 
      streamResponse.Close(); 
      myHttpWebResponse.Close(); 

     } 
    } 
} 
catch (WebException ex) 
{ 
    MessageBox.Show("something went wrong"); 
} 

錯誤代碼是404 Not Found,但不是一個消息,我得到了以下錯誤:

enter image description here

爲什麼例外從未被抓住?

回答

3

你可能有一次機會異常在Visual Studio再追開啓。

嘗試在沒有調試器的情況下運行應用程序(Ctrl + F5)。或者,如果你得到這個對話框,你可以按Run(F5)來獲得你的消息框。

0

你確定你'捕捉'相同類型的異常嗎?相反WebException抓的只是Exception,看看你是否得到MessageBox

try 
    { 
     using (var myHttpWebResponse = (HttpWebResponse) httPrequestCreated.GetResponse()) 
     { 
      var streamResponse = myHttpWebResponse.GetResponseStream(); 

      if (streamResponse != null) 
      { 
       var streamRead = new StreamReader(streamResponse); 
       var readBuff = new Char[256]; 
       var count = streamRead.Read(readBuff, 0, 256);   

       while (count > 0) 
       { 
        var outputData = new String(readBuff, 0, count); 
        finalResopnse += outputData; 
        count = streamRead.Read(readBuff, 0, 256); 
       } 
       streamRead.Close(); 
       streamResponse.Close(); 
       myHttpWebResponse.Close(); 

      } 
     } 

    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(string.format("this went wrong: {0}", ex.Message)); 
    } 

編輯:看着你的PIC緊密我覺得你以前見過的異常​​被拋出你的catch塊。在您VS按Ctrl + Alt + E鍵,並確保Throw檢查Common Language Runtime Exceptions選中

+0

'GetResponse()'不會拋出'WebException',這就是他所追求的,所以我不認爲這是問題所在。 – svick 2012-02-26 18:14:34

+1

如果他定義了自己的WebException(MyNamespace.WebException)並捕獲該WebException而不是System.Net.WebException,該怎麼辦? – sebagomez 2012-02-26 18:19:17

+0

一個和實際的'System.Net.WebException'完全一樣的消息嗎?這不太可能。 – svick 2012-02-26 20:16:45

相關問題