Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

basic - Problem with "try-catch" in a web request vb.net

I'm making a web request that completes successfully most of the time (target$ is a URL). But occasionally my code throws a valid exception, 404 not found, if the URL target$ doesn't exist, and execution stops. The code:

Sub scrape(target$)
    Dim request As WebRequest = WebRequest.Create(target$)
    Dim response As WebResponse = request.GetResponse()
    Dim dataStream As Stream = response.GetResponseStream()
    ' Open the stream using a StreamReader for easy access.
    Dim reader As New StreamReader(dataStream)
    ' Read the content.
    Dim responseFromServer As String = reader.ReadToEnd()
    txtResponse.Text = ""
    txtResponse.Text = responseFromServer
    ' Clean up the streams and the response.
    reader.Close()
    response.Close()

end sub

The exception, if thrown, happens in the second line, "Dim response...". So I tried adding a "try-catch" as shown.

Sub scrape(target$)
    Dim request As WebRequest = WebRequest.Create(target$)
    Dim response As WebResponse = request.GetResponse()
    Try
        Dim dataStream As Stream = response.GetResponseStream()
    Catch
        exflag = True
    End Try
    ' Open the stream using a StreamReader for easy access.
    Dim reader As New StreamReader(dataStream)
    ' Read the content.
    Dim responseFromServer As String = reader.ReadToEnd()
    txtResponse.Text = ""
    txtResponse.Text = responseFromServer
    ' Clean up the streams and the response.
    reader.Close()
    response.Close()

end sub

But now when I try to compile the code, VisualStudio tells me that "datastream is not declared" and the compile fails.

What am I doing wrong and how do I catch the exception when it's thrown?

Thanks...

question from:https://stackoverflow.com/questions/65892098/problem-with-try-catch-in-a-web-request-vb-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...