程序中,有时会遇到超时的异常,需要进行处理,用一般的try...catch(Exception ex)...会发现ex没有status属性,此时使用WebException捕获异常:
try { resp = (HttpWebResponse)req.GetResponse(); // ... } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null) { Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode); } else { // no http status code available } } else { // no http status code available } }