Try Catch Finally不会在所有代码路径上返回值

时间:2013-11-19 16:28:48

标签: 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.Publish(ex, ExceptionDestinationEmail, TSecurity.GetUserID)
        Finally
            If ds IsNot Nothing Then
                ds.Dispose()
            End If
        End Try
        Return ds
    End Function

我开始研究try catch最终流如何工作,并且我意识到在这种情况下,由于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

然后开始收到编译器警告: Function doesn't return a value on all code paths.

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

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

这是最好的方法吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

没关系,就在你调用该函数做类似的事情时,你知道你的数据集有一个值而没有进入catch语句:

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