views:

237

answers:

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?

+4  A: 

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

Marc Gravell
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.
pipTheGeek
+1  A: 

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

Vincent Van Den Berghe
thanks, that was the code I provided, the question was whether it it possible to access the return value.
GalleySlave
A: 

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!

GalleySlave