Is it legal and possible to access the return value in a finally block?

我只是一个虾纸丫 提交于 2019-12-12 14:40:01

问题


I wish to set a usererror string before leaving a function, depending on the return code and variable in the function.

I currently have:

Dim RetVal as RetType

try
...
if ... then
    RetVal = RetType.FailedParse
    end try
endif
...

finally
    select case RetVal
        case ...
            UserStr = ...
    end select
end try

return RetVal

Is it possible to use return RetType.FailedParse, then access this in the finally block?


回答1:


The only real way of doing this in C# would be to declare a variable at the start of the method to hold the value - i.e.

SomeType result = default(SomeType); // for "definite assignment"
try {
   // ...
   return result;
}
finally {
    // inspect "result"
}

In VB, you might be able to access the result directly - since IIRC it kinda works like the above (with the method name as "result") anyway. Caveat: I'm really not a VB person...




回答2:


Declare the variable out of the try block, and check in the finally block if it has been set.




回答3:


I was wondering whether in VB one could (legally) do:

Public Function MyFunc() as integer
    Try
      if DoSomething() = FAIL Then
        return FAIL
      end if

  Finally
      if MyFunc = FAIL then
          Me.ErrorMsg = "failed"
      endif
  End Try
End Function

I know setting MyFunc = FAIL is legal (as a hang-over from VB), is it write-only or readable? My concern it that this is poor coding as

if MyFunc = FAIL Then

is too similar to

if MyFunc() = FAIL Then

which has very different consequences!



来源:https://stackoverflow.com/questions/304847/is-it-legal-and-possible-to-access-the-return-value-in-a-finally-block

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