2011-09-17 10 views
5

WebException'ın GetResponse çağrısında nasıl davranılacağını ve yanıtın WebException Response'den nasıl alınabileceğine kafa karıştırıcı bir örnek buldum. İkinci bulmaca null cevabının atış olarak değerlendirilmesinin nedeni; Herhangi bir öneri?GetResponse WebException ve ex.Response null'ı atıyor

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

cevap

5

tepki null olmamalıdır - bu durumda yazar WebException bu istisna işleyicisi içinde ele alınamaz ve sadece yukarı yayılır söylüyor.

Yine bu istisna işleme ideal değildir - muhtemelen bilmek istiyorum bir durum oluştu neden yani .:

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; 
} 
İlgili konular