当前位置 : 主页 > 编程语言 > c语言 >

如何在vb.net中使用try catch并最终阻止?

来源:互联网 收集:自由互联 发布时间:2021-06-24
下面是我想使用try catch和finally块的代码但是我无法做同样的事情,我是编程的新手,请帮我介绍一下try catch,最后在vb.net下面的代码中阻塞,另外帮助编写finally块,我将检查连接是否打开,I
下面是我想使用try catch和finally块的代码但是我无法做同样的事情,我是编程的新手,请帮我介绍一下try catch,最后在vb.net下面的代码中阻塞,另外帮助编写finally块,我将检查连接是否打开,I Connection打开然后应该在finally块中关闭但是在检查之后.
如果

条件..

else
    'Try
        con.Open()
        adp = New OleDbDataAdapter("select * from Login ", con)

        adp.Fill(dt, "Login")
        Dim i As Integer
        For i = 0 To dt.Tables(0).Rows.Count - 1
            If (cbType.Text = dt.Tables(0).Rows(i).Item(1) And txtUname.Text = dt.Tables(0).Rows(i).Item(2) And txtPass.Text = dt.Tables(0).Rows(i).Item(3)) Then

                MDIParent1.Show()


                Exit Sub


            End If
            '                Catch ex As Exception


        Next

        MsgBox("You Are Not A Valid User!!", MsgBoxStyle.Information)
    End If
这很简单.

请看下面的代码.

Try

    'In this block your program will try to execute your code.
    'If it catches any runtime error it will go to the Catch Block straight away without executing the next code in your Try Block.
    'If there are no errors then Finally Block will be executed after Try Block. Catch Block will be skipped.

Catch

    'It will display the errors here.
    'So you can use Catch ex as exception.
    'If you want to see the errors in Messagebox you can write the below line.
    'MessageBox.Show(ex.Message)

Finally

    'If your program finds errors or not this block will be executed always.

End Try

因此,您可以在代码中使用Try … Catch,如下所示:

Dim ValidUser as Boolean = False

Try
        con.Open()
        adp = New OleDbDataAdapter("select * from Login ", con)

        adp.Fill(dt, "Login")
        Dim i As Integer

        For i = 0 To dt.Tables(0).Rows.Count - 1
            If (cbType.Text = dt.Tables(0).Rows(i).Item(1) And txtUname.Text = dt.Tables(0).Rows(i).Item(2) And txtPass.Text = dt.Tables(0).Rows(i).Item(3)) Then

                ValidUser = true


                Exit For


            End If

        Next

        If ValidUser = True
             MDIParent1.Show()
        Else
             MsgBox("You Are Not A Valid User!!", MsgBoxStyle.Information)
        End If

Catch ex As Exception

    MessageBox.Show(ex.Message)

Finally

    if con.State = ConnectionState.Open then
        con.close()
    End If

    ValidUser = False

End Try
网友评论