Why use Finally in Try … Catch

前端 未结 14 1981
鱼传尺愫
鱼传尺愫 2020-12-05 06:38

I see that the Finally in Try .. Catch will always execute after any parts of the execution of the try catch block.

Is it any different to

14条回答
  •  离开以前
    2020-12-05 07:03

    The Finally block will execute regardless of if the function exits because of an exception. (there are some exceptions to this rule, see this stackoverflow question for more info).

    For example:

    Try
        'Do something
    Catch ex As Exception
        if 'Some Condition
           throw ex
        else
           'Handle exception
    Finally
        'Do cleanup
    End Try
    

    In this case the Finally block will still be executed even though you may throw an exception out of the function.

    This is a good practice to get into because it ensures that your cleanup code always executes. Of course using the Resoource Acquisition Is Initialization idiom is a much cleaner way of ensuring that resources get cleaned up, but I'm not versed enough in VB.net to know if this is possible to do.

提交回复
热议问题