2011-09-17 13 views
5

WebExceptionをGetResponse呼び出しで処理する方法の例と、WebException応答から応答を抽出する方法について困惑している例があります。 2番目のパズルはnull応答がthrowとして扱われる理由です。なにか提案を?GetResponseがWebExceptionをスローし、ex.Responseがnullの場合

HttpWebResponse response = null; 
try 
{ 
    response = (HttpWebResponse) request.GetResponse(); 
} 
catch (WebException ex) 
{ 
    response = (HttpWebResponse)ex.Response; 
    if (null == response) 
    { 
     throw; 
    } 
} 

答えて

5

応答はnullしてはいけません - このケースでは、著者がWebExceptionは、この例外ハンドラ内で処理することはできませんし、それだけに伝播されると言っています。

はまだこの例外処理は理想的ではありません - あなたはおそらく知ってほしい 例外が発生した理由、すなわち:

catch (WebException ex) 
{ 
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) 
    { 
     var resp = (HttpWebResponse)ex.Response; 
     if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404 
     { 
      //file not found, consider handled 
      return false; 
     } 
    } 
    //throw any other exception - this should not occur 
    throw; 
} 
関連する問題