2011-06-11 46 views
2

當sub要求try/catch塊成功運行時,VB中的約定是什麼,但catch塊是否不會引發異常?在try/catch塊中處理錯誤

我可以把所有的代碼放到try塊中,但是這看起來很亂,因爲大部分代碼都不需要嘗試,只需要嘗試成功。

例如,catch塊應該退出sub?這將適用於我目前的情況,如果這是正確的程序,請告訴我,但更成功和失敗都需要額外處理的更一般情況如何?

+0

很難理解這一點。沒有處理異常處理的約定。也許你應該讓它成爲一個返回布爾值的函數,用False指示「它沒有工作」。 – 2011-06-11 18:12:59

回答

2

我就這麼沿着

Dim success As Boolean = False 

    Try 
     'Code to execute 
     success = True 
    Catch ex As Exception 
    End Try 

    If success Then 
     'success processing 
    Else 
     'failure processing 
    End If 
0

這是一個懸而未決的老問題線的東西,所以我儘量回答它或許可以幫助別人。

試試這個:

Dim successState As Boolean = True 
Try 
    ' Do something in here that 
    ' might raise an error. 
Catch 
    ' Handle exceptions that occur within 
    ' the Try block, here. 
    successState = False 
Finally 
    ' Perform cleanup code in here. 
End Try 

If successState Then 
    MessageBox.Show("Success!") 
End If 

當抓到錯誤時,會出現沒有成功對話框。