7

我收到此错误:

函数“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

我尝试了所有可能的解决方案,但没有奏效。任何帮助,将不胜感激。

4

2 回答 2

11

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
于 2013-09-10T14:50:44.257 回答
2

如果在 try..catch 块中抛出异常,则不会返回任何值。您要么需要提供返回值以防引发异常(通过在 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)
            ' Either do this:
            ' Return False
            ' or this:
            ' Throw ex
        Finally
            ' If Not cn Is Nothing Then cn.Close()
        End Try
    End Function
于 2013-09-10T14:50:46.263 回答