Vb.net 在函数中尝试Catch
我的代码中有一个错误,我认为没有任何方法可以避免它 我需要从这个函数中获取T1值,并在不使程序崩溃的情况下通过错误 无论如何,这是我的代码。我修改它只是为了让它看起来简单Vb.net 在函数中尝试Catch,vb.net,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
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
不要将引发异常的代码放在
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()
),我们将尝试帮助解决此问题。不要将引发异常的代码放在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()
),我们将尝试帮助解决问题。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块会增加编译器的开销,并会降低程序的速度。所以你应该避免在任何可以避免的地方尝试捕捉障碍
试试这个:
Dim PL As Integer = IIf(row <= 0, 0, dgv1.Rows(row - 1).Cells(1).Value)
Dim PL As Integer=IIf(行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)
Dim PL As Integer=IIf(row)这几乎是我尝试过的,但就像你说的,我没有把捕获放在我应该放的地方。谢谢你!这几乎是我尝试过的,但就像你说的,我没有把捕获放在我应该放的地方。谢谢你!