On Error Resger Next时出错

时间:2017-05-03 16:05:15

标签: .net vb.net compiler-errors

我无法构建exe:

  

1> ------程序集已启动:项目:B,配置:调试任何CPU

     

B.vb(38.9):错误BC36595:该方法不能同时包含   “On Error Resume Next”语句并定义使用的变量   在lambda表达式或查询表达式中。

     

组装:成功:0,有错误:1,无变化:0,跳过:0

从第37行到第48行:

Sub Read(ByVal ar As IAsyncResult)
    On Error Resume Next
    If TCP.GetStream.DataAvailable And TCP.GetStream.CanRead Then
        Dim tt As New Thread(AddressOf Data) : tt.IsBackground = True : tt.SetApartmentState(ApartmentState.STA) : tt.Start(DirectCast(bf.Deserialize(TCP.GetStream), Byte()))
        TCP.GetStream.Flush() : TCP.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
        Exit Sub
    Else
        GoTo r
    End If 
r:
    Disconnect()
End Sub

我正在尝试使用try \ catch,但不知道,这是正确的吗? :

Sub Read(ByVal ar As IAsyncResult)
    Try
        If TCP.GetStream.DataAvailable And TCP.GetStream.CanRead Then
            Dim tt As New Thread(AddressOf Data) : tt.IsBackground = True : tt.SetApartmentState(ApartmentState.STA) : tt.Start(DirectCast(bf.Deserialize(TCP.GetStream), Byte()))
            TCP.GetStream.Flush() : TCP.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
            Exit Sub
        End If
    Catch
        GoTo r
    Finally
    End Try
r:
    Disconnect()
End Sub

1 个答案:

答案 0 :(得分:0)

该错误消息上的documentation告诉您如何修复它:

  

更正此错误

     
      
  1. 将使用 On Error Goto 语句的异常处理代码替换为 Try ... Catch 语句。
  2.   

尝试... Catch 将包含以下部分:

  • Try - 应该执行什么
  • Catch - 如果在Try
  • 中引发异常,应执行的操作
  • Finally - 应该执行什么是否存在例外
  

我正在尝试使用try \ catch,但不知道,这是正确的吗?

可能有效,但Exit SubGoto是不必要的,并且会让事情变得混乱。我会尝试:

Sub Read(ByVal ar As IAsyncResult)
    Try
        If TCP.GetStream.DataAvailable And TCP.GetStream.CanRead Then
            Dim tt As New Thread(AddressOf Data) : tt.IsBackground = True : tt.SetApartmentState(ApartmentState.STA) : tt.Start(DirectCast(bf.Deserialize(TCP.GetStream), Byte()))
            TCP.GetStream.Flush() : TCP.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
        End If
    Catch
        Disconnect()
    Finally
    End Try
End Sub

但如果有异常,只调用Disconnect()似乎很奇怪。连接是否应保持打开?调用者如何知道是否已调用Disconnect