函数不会在所有代码路径上返回值.使用结果时,可能会在运行时发生空引用异常

Hel*_*Out 6 vb.net null return reference function

我收到这个错误:

函数'getkey'不会在所有代码路径上返回值.使用结果时,可能会在运行时发生空引用异常.

到以下代码:

 Public Function getkey(ByVal id As String)
            Dim cmd As SqlCommand
            Try
                cmd = New SqlCommand("dbo.getkeydesc", GenLog.cn)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@id", id)
                Dim r As SqlDataReader = cmd.ExecuteReader()
                If r.HasRows Then
                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                ' If Not cn Is Nothing Then cn.Close()
            End Try
        End Function
Run Code Online (Sandbox Code Playgroud)

我尝试了所有可能的解决方案但它们没有用.任何帮助,将不胜感激.

Dou*_*bin 10

Catch块不返回值.将其更改为返回值的位置,如下所示:

Public Function getkey(ByVal id As String)
        Dim cmd As SqlCommand
        Try
            cmd = New SqlCommand("dbo.getkeydesc", GenLog.cn)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@id", id)
            Dim r As SqlDataReader = cmd.ExecuteReader()
            If r.HasRows Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
            Return False
        Finally
            ' If Not cn Is Nothing Then cn.Close()
        End Try
    End Function
Run Code Online (Sandbox Code Playgroud)