【发布时间】: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