2011-06-11 73 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 

当抓到错误时,会出现没有成功对话框。