I saw this tip in another question and was wondering if someone could explain to me how on earth this works?
try { return x; } finally { x = null; }
I mean, does the finally
clause really execute after the return
statement? How thread-unsafe is this code? Can you think of any additional hackery that can be done w.r.t. this try-finally
hack?
Best Answer
The finally statement is executed, but the return value isn't affected. The execution order is:
Here's a short program to demonstrate:
This prints "try" (because that's what's returned) and then "finally" because that's the new value of x.
Of course, if we're returning a reference to a mutable object (e.g. a StringBuilder) then any changes made to the object in the finally block will be visible on return - this hasn't affected the return value itself (which is just a reference).