Why use Finally in Try/Catch

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • !NoItAll
    Contributor
    • May 2006
    • 297

    Why use Finally in Try/Catch

    OK, I'd like to know the difference between the following two blocks of code:

    Block A
    Code:
    Try
       Something
    Catch
       Process Errors
    End Try
    
    Do other things
    Block B
    Code:
    Try
       Something
    Catch
       Process Errors
    Finally
       Do other things
    End Try
    These seem to be equivalent to me, but I must be missing something. In both cases the "Do other things" code executes after errors are caught. I just can't see the point of the Finally block!
  • lotus18
    Contributor
    • Nov 2007
    • 865

    #2
    From the word finally itself, It still executes the statement even when there is an error occured in a catch block.

    Comment

    • !NoItAll
      Contributor
      • May 2006
      • 297

      #3
      So does any code that follows the Try-Catch block. Catch does not stop execution.

      Comment

      • !NoItAll
        Contributor
        • May 2006
        • 297

        #4
        I found the following in the C# area



        I think this explains it fairly well. Basically finally provides a block of code that will always execute. So - if you return in a catch, finally will still execute. I'm not sure I like the way code seems to execute in random order when it's in a finally block - but that may be my VBness coming through.

        So
        Code:
        Try
         Something
        Catch
         Return
        Finally
         Cleanup
        End Try
        
         More code here
        The cleanup will execute before the return statement, but none of the "more code here" will ever execute if there is an error. If there isn't an error then finally will still execute, followed by the code following the try block.
        I'm sure I will run into the need for this sometime...
        I'll keep it in my quiver.

        Comment

        Working...