The function does not return a value for all code codes. A null reference exception may occur at run time when the result is used

I get this error:

The 'getkey' function does not return a value for all code codes. An exceptional link exception may occur at runtime 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 did not work. Any help would be appreciated.

+4
source share
2 answers

The Catch block does not return a value. Change it so that it returns a value, for example:

 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 
+8
source

No value will be returned if an exception is added to this try..catch file. You must either provide a return value if an exception occurs (returning something in any catch block, or you need to rebuild 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 
+2
source

Source: https://habr.com/ru/post/1501496/


All Articles