Visual studio 试着抓住最后一个';t在所有代码路径上返回一个值

Visual studio 试着抓住最后一个';t在所有代码路径上返回一个值,visual-studio,try-catch,return-value,compiler-warnings,try-catch-finally,Visual Studio,Try Catch,Return Value,Compiler Warnings,Try Catch Finally,我在一段遗留代码中进行了大量重构,我发现: Public Function GetDocumentTypes() As DataSet Dim ds As DataSet = Nothing Try ds = SqlHelper.ExecuteDataset(Conn, "USP_DocumentTypes_Get") Catch ex As Exception ErrorHandler.Publis

我在一段遗留代码中进行了大量重构,我发现:

Public Function GetDocumentTypes() As DataSet
        Dim ds As DataSet = Nothing
        Try
            ds = SqlHelper.ExecuteDataset(Conn, "USP_DocumentTypes_Get")
        Catch ex As Exception
            ErrorHandler.Publish(ex, ExceptionDestinationEmail, TSecurity.GetUserID)
        Finally
            If ds IsNot Nothing Then
                ds.Dispose()
            End If
        End Try
        Return ds
    End Function
我开始研究try-catch-finally流是如何工作的,我意识到在这种情况下,由于finally语句的存在,ds将永远一文不值,然后我将代码更改为:

Public Function GetDocumentTypes() As DataSet
        Dim ds As DataSet = Nothing
        Try
            ds = SqlHelper.ExecuteDataset(Conn, "USP_DocumentTypes_Get")
            Return ds
        Catch ex As Exception
            ErrorHandler.Publish(ex, ExceptionDestinationEmail, TSecurity.GetUserID)
        Finally
            If ds IsNot Nothing Then
                ds.Dispose()
            End If
        End Try
    End Function
然后开始接收编译器警告:

最后,我解决了这样编写代码的问题:

Public Function GetDocumentTypes() As DataSet
        Dim ds As DataSet = Nothing
        Try
            ds = SqlHelper.ExecuteDataset(Conn, "USP_DocumentTypes_Get")
            Return ds
        Catch ex As Exception
            ErrorHandler.Publish(ex, ExceptionDestinationEmail, TSecurity.GetUserID)
            Return ds
        Finally
            If ds IsNot Nothing Then
                ds.Dispose()
            End If
        End Try
    End Function

这是最好的方法吗?

是的,这似乎是一种合理的方法。

很好,只要调用该函数,就可以这样做,这样您就知道您的数据集有一个值,并且没有出现在catch语句中:

if Not GetDocumentTypes is nothing then
'your code here
end if