问题
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?
回答1:
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...
回答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.
回答3:
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.
来源:https://stackoverflow.com/questions/5788134/return-in-the-finally-block-why-not