Friday, October 2, 2009

Will finally work if there is a return in catch

Confusing?? Just see the code below

Public Sub MyFun()
    Try
        Dim ope = 2
        Dim a As Integer = 10 / ope
    Catch ex As Exception
        MessageBox.Show("Exception")
        Return
    Finally
        MessageBox.Show("Finally")
    End Try
End Sub
This will execute properly and the finally will work.No doubt.But what about the below code.

Public Sub MyFun()
    Try
        Dim ope = 0
        Dim a As Integer = 10 / ope
    Catch ex As Exception
        MessageBox.Show("Exception")
        Return
    Finally
        MessageBox.Show("Finally")
    End Try
End Sub

There is no question that the above code will throw an exception.Then the catch will get executed which contains a return statement.Will that return statement works properly and go back to the calling function?


The answer is NO. The finally will execute even the catch contains a return.