Return in the Finally Block... Why not?

serhio picture serhio · Apr 26, 2011 · Viewed 17.6k times · Source

As MSDN mentions:

The code in a Finally block runs after a Return statement in a Try or Catch block is encountered, but before that Return statement executes. In this situation, a Return statement in the Finally block executes before the initial Return statement. This gives a different return value. To prevent this potentially confusing situation, avoid using Return statements in Finally blocks.

As I didn't understand a lot from this note, I'll take an example (VB.NET, I think in C# is the situation is similar):

Try
    HugeOp()
    Return "OK"
Catch
    Return "NOK"
Finally
    Return "Finally"
End Try

Now, why should be this illegal in both C# and VB.NET?

Answer

Thomas Levesque picture Thomas Levesque · Apr 26, 2011

It's illegal because when you reach the Finally block, the value to return is already defined ("OK" if everything went well, "NOK" if an exception was caught). If you were able to return a different value from the Finally block, this value would always be returned, whatever the outcome of the instructions above. It just wouldn't make sense...