Is it legal and possible to access the return value in a finally block?
Question
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?
Solution
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...
OTHER TIPS
Declare the variable out of the try block, and check in the finally block if it has been set.
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!