G'day... This is another one of those "Adam admits he's a bit thick, and doesn't RTFM" kind of posts.
Yesterday I was writing a function which loaded and read from a file, and extracted some info from it. It's entirely legit for the thing being sought to not be in the file, and the correct response in this case is to return an empty string. I wanted to deal with the chance of the file ops failing, so I wrapped the whole thing in a try/catch/finally as one is wont to do. I'll stop describing the code and just list it:
Can you see the stupid thing I've done here?
It seems straight fwd: I look for the value I'm after, return it if I find it, or if I get to the end of the file I return an empty string. If I encounter any problems, I just error, but make sure I close the file.
Except it doesn't work... I always got an empty string. The matching & extraction logic is fine (I checked): it just wasn't working.
After about 15min of swearing (this is an integral part of my troubleshooting process. Or actually pretty much any process I undertake ;-), I changed the return statement in the finally block to return "errored". So I started to get "errored" every time. But no exceptions were being raised... the code should be hitting my "success" return statement. And when I did some debugging, it... err... WAS being hit. But so was the one in the finally block.
It's then it occurred to me that finally always runs, whether there was an exception or not. I mean I know this, but I didn't get that it always runs no matter what. So the "success" return was running, which caused the try block to exit, and the finally block to run, and its return statement blitzed the earlier one. That behaviour was not what I was expecting, but it does make sense.
I tweaked the code to be more logically sound, as follows:
(note that all I did was move the second return outside of the finally block).
What do you think about this? Is it all obvious and I'm thick, or did this have you going "oh yeah: didn't think of that"?
Being thick is handy sometimes: one learns a lot more that way! ;-)
Time to jump off this train...