user3793009
user3793009

Reputation:

Try Catch Inside a Function

I have an error in my code and i don't think there is any way to avoid it.

I need to get the T1 value from this function and get past the error without crashing the program.

Anyway here is my code. I modified it just to make it look simple.

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

I've tried this solution and similar, but no matter where i put the try-catch-endtry, either i get an error, either the T1 value is not getting returned right.

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

Upvotes: 1

Views: 1252

Answers (2)

Pradeep Kumar
Pradeep Kumar

Reputation: 6979

A. You put the suspect code that can error out in the Try block, not the Catch block.

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. I don't think your code is really a good candidate for Try...Catch. You can easily avoid putting it in Try...Catch block. Note that setting up Try..Catch blocks has additional overheads for the compiler and will slow down your program. So you should avoid Try..Catch blocks wherever it can be avoided.

Try this:

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

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460238

Don't put the code that raised the exception in the Catch but in the 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

Note that I've commented out the line which raises the exception since you don't need the variable anyway.

But you should mention what exception you get. Post the full stacktrace(ex.ToString()) and we will try to help to fix the issue.

Upvotes: 2

Related Questions