【问题标题】:Exception handling issue in C#C#中的异常处理问题
【发布时间】:2011-08-10 09:46:21
【问题描述】:

我目前正在尝试在某些代码上添加异常处理程序。该代码只是创建了一个实例。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 

我试过了:

try 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 
}

catch(Exception ex)
{
    // code here
}

我收到以下编译错误:

错误 1 ​​当前上下文中不存在名称“请求”。

通过将 try on 添加到语句中。我错过了什么吗?

【问题讨论】:

  • 提示:我怀疑 OP 试图访问 catch 块中的request

标签: c# .net windows


【解决方案1】:

异常可能不是在您尝试创建请求时发生,而是在您尝试获取响应时发生:

HttpWebResponse response;
try 
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
    // Handle exception here
}

使用 try-catch 块时,您需要将失败的代码行括起来。 (您可能还需要阅读 the documentation 一些内容)。

请记住,在使用 try-catch 块时,您打算在 try 块之外使用的任何内容都需要相应地限定范围(如我在上面所做的那样,在 try 块之外删除它)。

【讨论】:

  • 实际上是这样,因为可能已经消耗了最大的可用请求数
  • @Johnathan 根据the documentation 的说法,create 抛出的唯一异常是由于 uri 无效或本地权限问题。在调用GetResponse 方法之前不会发送任何请求,因此Create 肯定不会抛出任何与连接相关的异常,因为它还没有发生!
【解决方案2】:

您似乎正在尝试在 try 块之外使用“请求”变量。 如果你想在 try/catch 块之后使用它,你需要在块之外声明它。

HttpWebRequest request;
try 
{
    request = (HttpWebRequest)WebRequest.Create(firstline); 
}
catch (Exception ex)
{
}
// Your request variable won't be destroyed now, you can use it here

【讨论】:

    【解决方案3】:

    我想你要找的是什么;

        try 
        {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
         HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse
         if(HttpWResp.StatusCode ==200)
        {
        //Sucessfull code
        }
        else
        {
            //fail   code
    
         }
    
    }
    
    catch(Exception ex)
    {
    // Exception codee here
    }
    

    【讨论】:

      【解决方案4】:

      我猜这个例外并没有出现在你认为的那一行。尝试添加一个Application level 异常处理程序。然后,使用Environment.StackTrace 跟踪应用程序失败所在的行。

      如果您使用的是 Visual Studio,请使用调试异常并检查引发公共语言运行时异常。

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2011-01-18
        • 2011-04-27
        • 2016-06-27
        • 2010-09-29
        • 1970-01-01
        相关资源
        最近更新 更多