【发布时间】: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