gpt4 book ai didi

vb.net - 如何在vb.net中使用try catch和finally block?

转载 作者:行者123 更新时间:2023-12-02 09:36:53 26 4
gpt4 key购买 nike

下面是我想使用try catch和finally block 的代码,但我无法这样做,我是编程新手,请帮我在vb中的下面的代码中引入try catch和finally block 。 net,还有助于编写finally block 的代码,我将在其中检查连接是否打开,我的连接已打开,那么它应该在finally block 中关闭,但在检查后。如果

条件..

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

关于vb.net - 如何在vb.net中使用try catch和finally block?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com