【问题标题】:Object variable or With block variable not set?未设置对象变量或 With 块变量?
【发布时间】:2013-07-01 21:19:09
【问题描述】:

运行程序时出现此错误:

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

【问题讨论】:

  • 你能发布异常的完整堆栈跟踪吗?
  • @antiduh 我是 VB.net 的新手,我如何在 VS 2012 中做到这一点?在某处设置断点?

标签: vb.net exception-handling


【解决方案1】:

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

例子:

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

欲了解更多信息,请阅读 MSDN WebRequest.Create Method (String)

【讨论】:

    【解决方案2】:

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

    这是一个demo,尽管我对time 变量的声明做了一点改动,并在WebRequest.Create() 上放了一个字符串,例如:

    Dim time As Date = Now
    

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

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

    A first chance exception

    【讨论】:

      【解决方案3】:

      问题很可能是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(您的选择)。

      【讨论】:

      • 我设置函数的方式是使用像这样的按钮将地址变量传递给函数 'textbox1.text = getData("somesite.com")'
      • 我不确定这与您的 null ref 异常有何关系。如果用户可以进入该网站,则应始终针对输入无效地址的情况进行编码并进行处理。
      猜你喜欢
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多