2011-09-17 3 views
5

GetResponse 호출에서 WebException을 처리하고 WebException Response에서 응답을 추출하는 방법에 대한 예를 발견했습니다. 두 번째 퍼즐은 null 응답이 throw로 처리되는 이유입니다. 어떠한 제안?GetResponse가 WebException을 throw하고 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; 
} 
관련 문제