Function doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used

扶醉桌前 提交于 2019-12-22 06:01:36

问题


I'm getting this error:

Function 'getkey' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.

to the following code:

 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

I tried all possible solutions and they didn't work. Any help would be appreciated.


回答1:


The Catch block doesn't return a value. Change it to where it returns a value, like so:

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



回答2:


No value will be returned if an exception is thrown in that try..catch block. You either need to provide a return value in case an exception is thrown (by returning something in either the catch block, or you need to rethrow the exception.

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


来源:https://stackoverflow.com/questions/18721925/function-doesnt-return-a-value-on-all-code-paths-a-null-reference-exception-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!