java tricky one!

Associate
Joined
26 Jan 2006
Posts
1,502
Hey,

I wonder in what order the following is executed.

Assume there is a vector v passed an argument to a method which has the following:

Code:
try{ return v.remove(0); } finally { updateGui(gui); }

The question is, does the element FIRST get removed from the vector and THEN the gui will be updated?

thanks
 
Correct.

v.remove happens, finally block executes, method returns whatever was removed from v.

I'd be inclined not to use a try finally block to do that though. On one hand it's clean (although to be fair, I'd say that is a hacky use of a try block), but on the other hand it is tricky code, some one may not even realise that the finally block could be executed due to the return statement in the try block.
 
Code in the finally block should really only be code that will work no matter what.

Does your update gui code rely on v.remove at all? If it does, I suggest you move it into the try block.

Finally is meant more for things like closing file streams and cleaning up othe resources that could be left lingering if a function fails.
 
Yes, the gui update relies on the element getting removed. The gui traverses the vector and draws the objects found, therefore it should ALWAYS happen after the removal.

I just like the "less code idea", but it can be done with
Code:
Object obj = v.remove(0); updateGui(gui); return obj;
I guess to avoid confusion and hackery :p

Just was not sure how exactly the finally clause works :)
 
If you don't already know about it, you may wish to look up the Observer/Observable design pattern or Model-View-Controller architecture. Though the code that you have written may already appear within such a design pattern or arch (the passing of gui looks suspect though ;)), just thought you may find it interesting though if you've never encountered it.
 
Back
Top Bottom