Why use Finally in Try ... Catch

awe picture awe · Jul 21, 2009 · Viewed 42.8k times · Source

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 just skip the Finally section and just run it after, outside the try catch block?

Example 1, Try ... Catch ... Finally ... End Try

    Try
        'Do something
    Catch ex As Exception
        'Handle exception
    Finally
        'Do cleanup
    End Try

Example 2, Try ... Catch ... End Try ... Do the finally stuff outside

    Try
        'Do something
    Catch ex As Exception
        'Handle exception
    End Try
    'Do cleanup

Answer

kemiller2002 picture kemiller2002 · Jul 21, 2009

Yes, it is different. Finally will always run (barring program crash). If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.