【问题标题】:Catch all GetResponse Exception types in C#在 C# 中捕获所有 GetResponse 异常类型
【发布时间】:2014-05-01 02:21:12
【问题描述】:

HttpWebRequest.GetReponse() 有4种异常MSDN:
- System.InvlaidOperationException
- System.Net.ProtocalViolationException
- System.NotSupportedException
- System.Net.WebException

我想捕获由 GetResponse() 引发的所有个异常,或者对所有 GetResonse() 异常使用一个 catch{},或者对 GetResponse() 引发的每种异常类型使用一个 catch{} ,并使用另一个 catch{} 捕获所有其他异常。

在我阅读的所有内容中,我只看到 WebException 被捕获。是因为它捕获了 GetResponse() 抛出的所有内容,还是因为其他异常更通用,会被其他人抛出?

考虑以下代码:

try  
{
    //a bunch of code...
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    //the rest of the try block...
}
catch (WebException e)
{
    Console.WriteLine("You caught a WebException: " + e.Message);
    throw;
}
catch (Exception e)
{
    Console.WriteLine("This exception was not from getResponse: " + e.Message);
    throw;
}

*我故意扔在这里。它需要由堆栈中的其他调用者处理。

或者,要捕获 GetResponse 抛出的所有异常,我会做这样的事情吗?

catch (WebException e)
{
    Console.WriteLine("You caught a WebException: " + e.Message);
    throw;
}
catch (InvalidOperationExceltion e)
{
    // Do stuff...
}
catch (ProtocolViolationException e)
{
    // Do stuff...
}
catch (NotSupportedException e)
{
    // Do stuff...
}
catch (Exception e)
{
    // Do stuff...
}

我确信它和我想的一样简单,但我找不到比 WebException 更多的例子。

谢谢!

【问题讨论】:

    标签: c# exception exception-handling try-catch


    【解决方案1】:

    使用第二个代码,但是当您已经在处理 GetResponse 抛出的异常时,为什么还要处理所有其他异常呢?额外的“捕获”是不必要的 IMO。

    【讨论】:

    • 好问题。上面的代码有点误导。我的真实代码中的 try-catch 是围绕调用一个实际执行 GetResponse() 的方法,并且其中包含其他也可能失败的功能代码。通用 catch 包含特定的日志记录代码。
    • 除非有一种方法可以将对象参数传递给一个 catch{},它包含来自 getResponse() 的所有可能异常(相对于 catch 中的 if 语句),否则我会将其标记为已解决!感谢您及时回答 Anwarrex!
    • 这里可能会说明解决方案? stackoverflow.com/questions/136035/…
    • 该线程中的类似问题。我想问我的问题的简化方法是:异常类型可以按抛出者分组并被捕获吗?
    • 示例:methodExceptions = Exception.type.fromMethod(fooMethod)
    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多