Return in the Finally Block… Why not?

老子叫甜甜 提交于 2019-12-09 14:09:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!