开发者

Handling errors in try/catch blocks

开发者 https://www.devze.com 2023-03-12 19:36 出处:网络
What is the convention in VB when a sub requires that a try/catch block succeed in order to functio开发者_C百科n, but the catch block doesn\'t bubble the exception up?

What is the convention in VB when a sub requires that a try/catch block succeed in order to functio开发者_C百科n, but the catch block doesn't bubble the exception up?

I could put all of the code into the try block, but this seems messy since most of it doesn't need to be tried, it just needs the try to have succeeded.

For example, should the catch block exit the sub? This would work in my current situation, and if it is the proper procedure, let me know, but what about the more general scenario where both both success and failure require additional processing?


I would so something along the lines of

    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


This is an unanswered old question, so I try to answer it perhaps can help someone else.

Try this:

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

When it catch error, no success box will appear.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号