有没有一种方法可以获取在catch块中调用的WebException响应,但是请在try块中查看响应

时间:2019-06-11 16:15:33

标签: c# try-catch

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

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

1 个答案:

答案 0 :(得分:1)

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

try
{
    DoTheUsual();
}
catch(WebException webEx)
{
    //we won't need an if condition in here because we have the exception
    DoSomething();
}

,您可以在末尾抛出一个finally块,无论执行何种操作,该块都会始终执行。因此,我们绝对需要检查条件以查看响应是否不为空。

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();
}
相关问题