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

3

3

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?

Gravity answered 20/11, 2008 at 10:14 Comment(0)
S
4

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

Sealskin answered 20/11, 2008 at 10:18 Comment(1)
You are correct, VB treats the function name as just another local variable. The function return value is whatever value this magic local variabel has when the function ends.Thereby
H
1

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

Heady answered 20/11, 2008 at 10:28 Comment(1)
thanks, that was the code I provided, the question was whether it it possible to access the return value.Gravity
G
1

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!

Gravity answered 5/12, 2008 at 14:52 Comment(1)
You don't actually say this works, which it does. And the adding of () to cause recursion is always an issue with functions with no required arguments, so you just need to check for it.Goodbye

© 2022 - 2024 — McMap. All rights reserved.