1

运行程序时出现此错误:

Microsoft.VisualBasic.dll 中出现了“System.NullReferenceException”类型的第一次机会异常

对象变量或未设置块变量

这是我的代码:

    Dim rt As String = ""
    Dim out As String
    Dim wRequest As WebRequest
    Dim wResponse As WebResponse
    Dim SR As StreamReader
    Dim time As Date

    time = Now()

    Try
        wRequest = WebRequest.Create(Address)
        wRequest.Timeout = 10000
        wResponse = wRequest.GetResponse
        SR = New StreamReader(wResponse.GetResponseStream)
        rt = SR.ReadToEnd
        SR.Close()
    Catch wex As WebException

        Dim status As WebExceptionStatus = wex.Status

        If status = WebExceptionStatus.Timeout Then
            MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Timed Out", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        ElseIf status = WebExceptionStatus.ConnectFailure Then
            MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        ElseIf status = WebExceptionStatus.ProtocolError Then
            MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Protocol Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)

        End If

    End Try
4

3 回答 3

0

我正在检查你的代码,它工作正常。

这是一个演示,尽管我对变量的声明做了一些改动,time并在上面添加了一个字符串,WebRequest.Create()例如:

Dim time As Date = Now

WebRequest.Create("https://www.google.fm")

根据我自己的搜索,这种错误没什么好担心的,请参阅下面的链接。

第一次机会例外

于 2013-07-04T02:11:17.327 回答
0

问题很可能是因为为空wResponse.GetResponseStream而失败。wResponse(这可能是因为您的 Address 变量无效)。

尝试添加

Catch ex As Exception

    MessageBox.Show("Some other error occurred: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning)

End Try

在您的 WebException Catch 块之后查看问题所在。

或者只是放一个断点SR = New StreamReader(wResponse.GetResponseStream)并查看 wResponse(您的选择)。

于 2013-07-04T02:26:40.307 回答
0

您的错误的根源可能是您的Address变量。请尝试http://在前面加上前缀。

例子:

Address = "http://www.google.com"

有关更多信息,请阅读 MSDN WebRequest.Create Method (String)

于 2013-07-04T02:04:44.013 回答