2011-08-10 54 views
-7

我目前正在嘗試在某些代碼上添加異常處理程序。該代碼只是創建一個實例。C#中的異常處理問題

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 

我曾嘗試:

try 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 
} 

catch(Exception ex) 
{ 
    // code here 
} 

我得到以下編譯錯誤:

Error 1 The name 'request' does not exist in the current context.

通過添加試穿的語句。我錯過了什麼嗎?

+1

提示:我懷疑OP試圖訪問catch塊中的request。 – Kev

回答

2

的機會,在異常發生不是當你嘗試創建的要求,但是當你試圖得到響應:

HttpWebResponse response; 
try 
{ 
    response = (HttpWebResponse)request.GetResponse(); 
} 
catch (Exception ex) 
{ 
    // Handle exception here 
} 

當使用try-catch塊,你需要圍繞線代碼失敗。 (你可能需要更多地閱讀the documentation)。

請記住,當使用try-catch塊時,您打算在try塊之外使用的任何內容都需要相應地進行限定範圍(除了try塊之外,正如我上面所做的那樣)。

+0

實際上,這是因爲最大可用請求可能已被使用 –

+0

@Johnathan根據[文檔](http://msdn.microsoft.com/en-us/library/bw00b1dc.aspx)唯一的例外創建將由於無效的uri或本地權限問題。直到GetResponse方法被調用,纔會發送請求,所以任何連接相關的異常肯定不會被'Create'拋出,因爲它現在還沒有發生! – Justin

0

我認爲你在找什麼;

try 
    { 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 
    HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse 
    if(HttpWResp.StatusCode ==200) 
    { 
    //Sucessfull code 
    } 
    else 
    { 
     //fail code 

    } 

} 

catch(Exception ex) 
{ 
// Exception codee here 
} 
0

我想這個例外並不在你所想象的那一行中。嘗試添加Application level異常處理程序。然後,使用Environment.StackTrace跟蹤應用程序失敗的行。

如果您使用的是Visual Studio,請使用調試異常並檢查引發公共語言運行時異常。

希望它有幫助。

1

看來你試圖在try塊外使用你的「request」變量。 如果你想在try/catch塊之後使用它,你需要在塊外聲明它。

HttpWebRequest request; 
try 
{ 
    request = (HttpWebRequest)WebRequest.Create(firstline); 
} 
catch (Exception ex) 
{ 
} 
// Your request variable won't be destroyed now, you can use it here