Home > other >  Not catching exceptions even though it is inside try catch?
Not catching exceptions even though it is inside try catch?

Time:12-01

I am deleting a row inside a DataGridView and when there is no more row this pops up.


    Private Sub materialsGridView_SelectionChanged(sender As Object, e As EventArgs) Handles materialsGridView.SelectionChanged
        Try
            materialSelectedindex = materialsGridView.CurrentRow.Index
        Catch ex As Exception
            materialSelectedindex = -1
        End Try
    End Sub

    Private Sub delRowBtn_Click(sender As Object, e As EventArgs) Handles delRowBtn.Click
        If (materialSelectedindex = -1) Then
            MsgBox("Please select a row")
            Return
        End If
        materialsGridView.Rows.RemoveAt(materialSelectedindex)
    End Sub

Here is an image enter image description here

Why is it not catching even though it is inside a try catch?

CodePudding user response:

Look at the Exception Assistant window. See how the box is checked that says "Break when this exception type is thrown"? If you don't want the debugger to break when that exception type is thrown, uncheck that box. That is only happening because you're running in the debugger. If you run the application without debugging, which you can do either directly or using the VS toolbar of pressing Ctrl F5, then the exception will be caught.

By the way, it's generally bad practice to catch the base Exception type. You should catch only the specific exceptions that you reasonably believe could be thrown. Otherwise, you might be allowing a situation that you didn't count on and which might end up causing data corruption or the like.

You should also generally avoid exceptions being thrown in the first place, by validating the data you intend to use. In your case, you should check whether CurrentRow is Nothing first and then only use it if it's not. You could do this:

materialSelectedIndex = If(materialsGridView.CurrentRow Is Nothing,
                           1,
                           materialsGridView.CurrentRow.Index)

or you could do this:

materialSelectedIndex = If(materialsGridView.CurrentRow?.Index, 1)

The first option is basically an If...Then...Else while the second option uses the first value unless it's Nothing, in which case it uses the second value. The ?. operator will stop evaluation of the expression if what precedes it is Nothing, otherwise it behaves like a regular . operator.

  • Related