我目前正在尝试在某些代码上添加异常处理程序。该代码只是创建一个实例。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
我试过了:
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
}
catch(Exception ex)
{
// code here
}
我收到以下编译错误:
错误1当前上下文中不存在名称“request”。
将try on添加到语句中。我错过了什么吗?
答案 0 :(得分:2)
如果您尝试创建请求,但是当您尝试获取响应时,可能会发生异常:
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
// Handle exception here
}
使用try-catch块时,您需要包围失败的代码行。 (您可能需要阅读更多the documentation)。
请注意,在使用try-catch块时,您打算在try
块之外使用的任何内容都需要相应地限定范围(在try块之外进行delcare,如上所述)。 / p>
答案 1 :(得分:1)
您似乎试图在try块之外使用“request”变量。 如果要在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
答案 2 :(得分:0)
我认为你在寻找的是什么;
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
}
答案 3 :(得分:0)
我想那个异常并没有出现在您认为的那一行中。尝试添加Application level异常处理程序。然后,使用Environment.StackTrace
跟踪应用程序失败的行。
如果您使用的是Visual Studio,请使用调试例外并检查“公共语言运行时异常”。
希望它有所帮助。