25

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?

14
  • 3
    As I always recommend, just make a small test program to emulate the case and see for yourself.
    – Dmitry
    Commented Apr 26, 2011 at 9:04
  • 3
    it is illegal in C# (edit: and, it seems, VB) Commented Apr 26, 2011 at 9:04
  • 1
    @Mitch Wheat: The question was WHY this
    – serhio
    Commented Apr 26, 2011 at 9:05
  • 2
    @serhio ah, then MSDN is confusing ; a better remark in MSDN would be "avoid using Return statements in Finally blocks, else your code won't compile"; I have annotated MSDN to this effect. Commented Apr 26, 2011 at 9:06
  • 5
    An interesting side note: this is not illegal in JavaScript. function m() { try { return 1; } finally { return 2; } } a call to m() will return 2. Implementing that was a real pain for the development team. It's also legal in Java. Commented Apr 16, 2013 at 15:49

4 Answers 4

33

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...

8
  • thank you. So "Finally" should be the return value. Made illegal to "de-confuse" the code.
    – serhio
    Commented Apr 26, 2011 at 9:17
  • 1
    No, the return value is set before the return statement is executed. Inbetween those two things, the finally block is executed. It therefore makes no sense to have a return statement in a finally block. It doesn't make sense to say that finally "should" be the return value because it doesn't makes sense for finally to have a return value.
    – izb
    Commented Apr 26, 2011 at 9:22
  • @izb: In other words, in my success case, the compiler takes "OK" as return value, executes the Finally block, then takes the "OK" and effectively returns it?
    – serhio
    Commented Apr 26, 2011 at 9:26
  • 12
    The specification could define the behavior of return in a finally statement however it likes. It could return the old return value, the new return value or be illegal. Any if these behaviors is possible, and they chose to make it illegal. And I agree with that decision. Commented Apr 26, 2011 at 9:58
  • 1
    This has nothing to do with the return value being set already. You could delete the first two returns and you'd get the same error,.
    – usr
    Commented Jun 26, 2016 at 13:09
2

I guess the answer is in the question. It's illegal because it's confusing. It's not intuitive which value will be returned. If it's illegal, you are forced to write code where the flow is much clearer.

6
  • "confusing", "intuitive", but really what should be the return here after the compiler rules? Is it always "Finally"?
    – serhio
    Commented Apr 26, 2011 at 9:12
  • 1
    Looks like the compiler rules state it's illegal and shouldn't compile. So the question what it does return makes no sense. Commented Apr 26, 2011 at 9:16
  • @CodeInChaos: read the note I posted. "This gives a different return value."
    – serhio
    Commented Apr 26, 2011 at 9:19
  • You're note is obviously inaccurate and doesn't describe the behavior of either C# or VB.net. That's why @MarcGravell suggested that the documentation should be updated to be consistent with the actual behavior of the compiler. Commented Apr 26, 2011 at 9:31
  • 2
    Making it a warning would violate the spec. "8.9.4 The return statement" - "It is a compile-time error for a return statement to appear in a finally block" (From the C# specification) Commented Apr 26, 2011 at 9:56
2

I was curious about this, I'm running VS2010 and does not allow a Return in the finally block. here is the code I compiled

Public Class Class1
   Public Shared Function test() As String
      Try
         Return "OK"
      Catch ex As Exception
         Return "Catch"
      Finally
         test = "Finally"
      End Try
   End Function
End Class

I compiled the DLL to view the MSIL it looked rather interesting the above code basically gets refactored to this:

Public Class Class2
   Public Shared Function test() As String
      Try
         Try
            test = "OK"
         Catch ex As Exception
            test = "Catch"
         End Try
      Finally
         test = "Finally"
      End Try

      Return test
   End Function
End Class

and testing this out, the MSIL for the above two classes is exactly the same.

1
  • so, finally, you found a way to return in finally block in Visual Basic, using the function's name, even if confusing, there is a way to do it...
    – serhio
    Commented Apr 21, 2013 at 7:27
0

The reason that return statements aren't allowed in finally blocks ultimately comes down to the point/ goal of those structures.

Finally blocks are special blocks of code intended to always run start to finish, after some previous control structure has finished executing; they're primarily for "cleanup"-type code.

If we take the code provided:

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

The Finally block will be executed after the Return from either the Try or Catch.

This does kind of mean that having a Return there would "always return the same thing", but it's more than that– a Return already happened in the current procedure! What should that instruction even mean? Where are we returning to?

In the general case, a Return makes no sense within a Finally because having a statement that transfers control outside of these blocks is 1) antithetical to their purpose, and 2) hard to even conceptualize, since Finally blocks break the "standard" control flow when they run since they come after the Return of some previous control structure.

In C#, gotos are disallowed in finally blocks for essentially the same reason: external control transfer is just off limits within finally by design.


JavaScript can serve as an example here of how confusing things could be without this rule: in JS, finally blocks execute immediately before a control-flow statement (e.g. return) in try/ catch, but do allow returns inside themselves– which will overshadow (override) the return inside the try/ catch, if it exists.

I'd argue there's no resolution to this problem that's not confusing, other than just outright disallowing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.