我已经将一些控件从 VB6 迁移到 VB.Net 并且其中一个只读属性具有"下次出错时恢复"。 因此,该属性不会引发任何错误,它将始终返回一个值。
现在我用 try-catch 替换了它,我希望你们的意见是 try-catch 实现是否有效或需要任何更改。
下面,我展示了原始代码以及 try-catch 实现代码。
原始向导迁移的代码
Public ReadOnly Property TotalAmount() As String
Get
'On Error Resume Next
Dim intIndex As Short
Dim numFS As Short
Dim totalAmount As Double
With m_udtProperties_READ
numFS = CShort(UBound(m_udtProperties_READ.FundSource))
If numFS >= 0 Then
For intIndex = 0 To numFS
totalAmount = totalAmount +
CDbl(m_udtProperties_READ.FundSource(intIndex).FromSide.Amount)
Next
End If
TotalAmount= CStr(totalAmount)
End With
End Get
尝试捕获实现代码。
Public ReadOnly Property TotalAmount() As String
Get
Dim intIndex As Short
Dim numFS As Short
Dim totalAmount As Double
With m_udtProperties_READ
Try
numFS = CShort(UBound(m_udtProperties_READ.FundSource))
Catch ex As Exception
End Try
If numFS >= 0 Then
For intIndex = 0 To numFS
Try
totalAmount = totalAmount + CDbl(m_udtProperties_READ.FundSource(intIndex).FromSide.Amount)
Catch ex As Exception
End Try
Next
End If
TotalAmount = CStr(totalAmount)
End With
End Get
End Property
还有比上面更好的方法吗?
当你需要将代码从vb6转换为.net时,on error resume next
是令人讨厌的。
基本上,这意味着简单地忽略它之后的任何错误,并从引发错误的代码行继续执行代码。
在 .Net 中,执行等效的操作意味着on error resume next
所在的位置之后的每一行都应包装在带有空捕获的try...catch
块中。
显然,这是不切实际的,也不是好的做法(事实上,吞下例外是一种非常糟糕的做法(。
对于每个翻译代码的人来说都是幸运的,并不是每一行都可能引发异常。
您需要隔离翻译后代码中的危险区域,并且仅将它们包装在try...catch
中。
我建议不要吞下异常,而是将它们传播到可以处理它们的地方 - 所以我的建议是进行重构而不仅仅是翻译。