对象变量或With块变量未设置?

时间:2013-07-04 01:34:48

标签: vb.net exception-handling

我运行程序时遇到此错误:

  

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

3 个答案:

答案 0 :(得分:0)

您的错误来源可能是您的Address变量。 请尝试使用前面的http://作为前缀。

示例:

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

有关更多详情,请参阅MSDN WebRequest.Create Method (String)

答案 1 :(得分:0)

我正在检查你的代码,它运行正常。

这是一个demo,虽然我对time变量的声明进行了一些更改,并将字符串放在WebRequest.Create()上,如:

Dim time As Date = Now

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

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

A first chance exception

答案 2 :(得分: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(您的选择)。