尝试在功能内捕捉

时间:2014-08-14 11:14:39

标签: vb.net

我的代码中有错误,我认为没有办法避免它。

我需要从此函数中获取T1值并在不崩溃程序的情况下通过错误。

无论如何,这是我的代码。我修改它只是为了让它看起来很简单。

Dim T1 as Integer
Dim L1 As Integer = dgv1.Rows(row).Cells(2).Value
Dim E1 As Integer = dgv1.Rows(row).Cells(3).Value
Dim PL As Integer = dgv1.Rows(row - 1).Cells(1).Value '(Here i get the error)

If blabla = True Then
    If L1 = 0 Then T1 = E1 + P1
end if

Return T1

我已经尝试过这个解决方案并且类似,但无论我在哪里放置try-catch-endtry,要么我得到一个错误,要么T1值没有正确返回。

Dim T1 as Integer

Try
Catch ex As Exception
    Dim L1 As Integer = dgv1.Rows(row).Cells(2).Value
    Dim E1 As Integer = dgv1.Rows(row).Cells(3).Value
    Dim PL As Integer = dgv1.Rows(row - 1).Cells(1).Value

    If blabla = True Then
        If L1 = 0 Then T1 = E1 + P1
    end if

    Return T1
End Try

Return T1

2 个答案:

答案 0 :(得分:2)

不要将引发异常的代码放在Catch中,而是放在Try中:

Dim T1 as Integer
Try
    Dim L1 As Integer = dgv1.Rows(row).Cells(2).Value
    Dim E1 As Integer = dgv1.Rows(row).Cells(3).Value
    'Dim PL As Integer = dgv1.Rows(row - 1).Cells(1).Value

    If blabla = True Then
        If L1 = 0 Then T1 = E1 + P1
    end if

    Return T1
Catch ex As Exception
    ' log this exception
End Try
Return T1

请注意,我已经注释掉引发异常的行,因为您无论如何都不需要变量。

但是你应该提到你得到的异常。发布完整的堆栈跟踪(ex.ToString()),我们将尝试帮助解决问题。

答案 1 :(得分:2)

A. 您将可疑错误的可疑代码放在Try块中,而不是Catch块。

Try
    ' the code that can cause errors goes here

Catch ex As Exception
    ' put code to do whatever happens if the code in Try block error out
    ' e.g. Show a messagebox informing the user etc.

End Try

B。我不认为您的代码真的是Try ... Catch的合适人选。您可以轻松避免将其放入Try ... Catch块中。请注意,设置Try..Catch块会为编译器带来额外的开销,并会降低程序的速度。因此,您应该避免在可以避免的任何地方使用Try..Catch块。

试试这个:

Dim PL As Integer = IIf(row <= 0, 0, dgv1.Rows(row - 1).Cells(1).Value) 
相关问题