2013-05-29 39 views
3

下面是我想使用try catch和finally塊的代碼但是我無法做同樣的事情,我是編程新手,請幫我介紹try catch並最終在vb.net中阻止下面的代碼,還有助於編寫finally代碼塊,我將檢查連接是否打開,I Connection打開,然後它應該在finally塊中關閉,但在檢查之後。 如果如何使用try catch並最終在vb.net中阻止?

條件..

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 
+1

這也許應該是['Using'聲明】(http://msdn.microsoft.com/無論如何,en-us/library/htd05whh(v = vs.80).aspx)。 – vcsjones

+0

如果您的嘗試在for循環之外,那麼catch必須也在外面。 –

+0

謝謝@ the_lotus ..它的工作原理,可以üPLZ幫助代碼終於塊我在哪裏檢查連接是否打開,我連接打開,那麼它應該關閉在finally塊,但在檢查 –

回答

12

這是非常簡單的。

請看下面的代碼。

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 
+0

@vishal嗨,我不確定我看到把代碼放在'Finally'子句和'End Try'後面的區別?請問有什麼機會可以爲我嘗試並詳細闡述這一點?謝謝! – Pezzzz

+0

一般來說,如果你在finally代碼塊中寫入代碼或者在結束之後嘗試沒有任何區別。但是,如果您想要意外關閉try塊,我的意思是如果您在Try或Catch塊中使用Exit Try,Finally塊將不會被執行。我可能是錯的,因爲我沒有嘗試過。 – Vishal