【问题标题】:Properly handling exceptions generated by WebRequest and WebReponse in .NET在 .NET 中正确处理由 WebRequest 和 WebReponse 生成的异常
【发布时间】:2014-08-22 05:48:11
【问题描述】:

在浏览 MS 示例和 Stackoverlow 示例时,我发现了很多处理异常或不处理异常的示例t 处理异常。

一个例子,我觉得很有趣的是https://stackoverflow.com/a/137300/465292 usingusing

另一个例子(来自https://stackoverflow.com/a/3279967/465292

var request = WebRequest.Create(requestUri) as HttpWebRequest;
                  if (request != null)

对我来说似乎是假的,因为文档中没有。 http://msdn.microsoft.com/en-us/library/bw00b1dc%28v=vs.110%29.aspx, WebRequest.Create() 返回null

Microsoft 自己的示例 http://msdn.microsoft.com/en-us/library/es54hw8e%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1,将 WebRequestWebReponse 放在一个 try 块中。

【问题讨论】:

  • 对于您的“另一种情况”:WebRequest.Create("ftp://some.site") as HttpWebRequest 确实会返回 null -“Create 方法返回 WebRequest 的后代”,但并非一直都需要 HttpWebRequest
  • @AlexeiLevenkov,好吧,如果 WebRequest.Create("address") 返回 null,则表示不支持方案。让WebRequest.Create() 抛出NotSupportedException 异常不是更好吗?编辑:好吧,没必要……如果您请求 ftp 地址,并期望 HttpWebRequest 作为响应(as HttpWebRequest),那是的。 null 会是更好的选择!

标签: c# asp.net .net exception exception-handling


【解决方案1】:

简而言之,这取决于。 try / catch 块的意义在于,如果你认为你可以从那个时间点抛出的异常中恢复过来。 IE。如果您怀疑网络通话应该可以正常工作并想在放弃之前尝试几次,您会重新尝试吗?

这是根据具体情况而定的。如果发生异常并且您不能/不想处理它,那么不要打扰try / catch 并让它上升,直到有东西可以处理它。

using 一样,这允许您释放内存并且嵌套usings 很好,因为它确保您在可能的情况下处理对象。当然,根据您的操作,您可能希望在finally 中明确地使用try / catch / finallydispose,但同样需要逐案处理。

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 2011-01-21
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多