[02/03] How final is Finally?
Just a quick question, would code in the Finally block of a Try statemnet get executed if I use Exit Sub in the Catch block? MSDN states "absolutely, by all means, always" but not explicitly about Exit Sub and I am kind of sceptical.
To reproduce the case just to check it would take some time so I decided to ask here if someone knows.
Thanks
Re: [02/03] How final is Finally?
Well, you could always just run a small test, as I just did. But seeing as how I've already done it, I'll tell you.
The Finally block gets run through always, regardless of a Return or Exit statement.
Re: [02/03] How final is Finally?
Yeah, I played around with this a few months back, and posted a thread on it. I found it a bit odd that a return statement anywhere prior to the Finally block was actually hitting the finally block. It appears that when you implement a Try....Catch block (whether there is a finally, or not), the behavior of the Try block is much like a function in itself. The Exit Sub, or Return statement will exit the code you are in, but run any Finally block, before exiting the outer sub.
I can understand why this was done, but it is kind of odd. When the Finally block is hit, the variables in the sub/function can be in an undeterminate state (some might not be initialized yet, or perhaps they have been). An early exit in a Try block may not be an early exit at all.
Re: [02/03] How final is Finally?
One of the reasons to do so was to relaes recources even if ther was a little mishap... like files might were opened for reading should be released.
and in VB.Net you can determine if a variable was or wasn't initialized.
so that wouldn't be a prob neither.
Re: [02/03] How final is Finally?
Yes, you can determine whether a variable was or wasn't initialized, but if you forget to, and it wasn't, then your Finally block will throw, which is often not what you expect.