【问题标题】:Try Catch Finally doesn't return a value on all code pathsTry Catch finally 不会在所有代码路径上返回值
【发布时间】:2013-11-19 16:28:47
【问题描述】:

我正在对遗留代码进行大量重构,结果发现:

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

这是最好的方法吗??

【问题讨论】:

    标签: visual-studio try-catch return-value compiler-warnings try-catch-finally


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      没关系,只是当你调用那个函数时做这样的事情,这样你就知道你的数据集有一个值并且没有进入 catch 语句:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 2018-11-05
        • 2021-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-28
        相关资源
        最近更新 更多