C# 有没有一种方法可以获取在catch块中调用的WebException响应,但可以在in-try块中看到响应

C# 有没有一种方法可以获取在catch块中调用的WebException响应,但可以在in-try块中看到响应,c#,try-catch,C#,Try Catch,因此,基本上我希望能够使用从WebException返回的响应,并将其添加到if语句中,但我不确定是否有办法在响应到达捕获点之前捕获它 try { var respnse = //WebException Response if(response == '') DoSomething() } catch (WebException exception)

因此,基本上我希望能够使用从WebException返回的响应,并将其添加到if语句中,但我不确定是否有办法在响应到达捕获点之前捕获它

       try
        {  
         var respnse =  //WebException Response 
        if(response == '')
          DoSomething()    
        }
        catch (WebException exception)
        {
        }

您将无法捕获
try
块中的任何异常。但是,可以在
catch
块内
DoSomething()

try
{
    DoTheUsual();
}
catch(WebException webEx)
{
    //we won't need an if condition in here because we have the exception
    DoSomething();
}
您可以在最后抛出一个
最后
块,该块将始终执行,无论发生什么情况。所以我们肯定需要检查条件,看看响应是否不是null

WebException response = new WebException();
try
{
    DoTheUsual();
}
catch(WebException webEx)
{
    response = webEx;
}
finally
{
    //If an exception occured, DoSomething() will execute, 
    //else your code will move on
    if (response != null) DoSomething();
}

抓到的就是你抓住它的地方。这就是所谓的捕获。这就是它所做的:它捕获异常。你只需要编写你想要的代码。在try/catch之外声明
响应
。如果需要对异常执行某些操作,请在
catch
中执行。属于
WebException
响应只在引发
WebException
时可用。你不能在手之前使用它,因为在那一点上它不存在。不过,您可以在
catch
部分中使用它。。。