Let's get philosophical for a moment. What is History? It's not the past, it's someones recollection of the past. So.. what is the execution stack. We like to think it's the history yeah? Well, what if you could rewrite it too?
You can! In Smalltalk at least (And C, but you'll be struggling in other languages to do it easily). Seaside does this with Continuations, but that's not the only place you'll find this whacky history-rewriting. You'll also find it in your friendly VW debugging simulator.
And, now you'll also find it in the package BeforeYouLeave that I've just published to public store. I had my mad scientist hat on last Friday when I was trying to solve a particular problem to do with inserting #ensure: like logic without having to wrap everything up in a block.
So what did I concoct? Well, basically, it inserts a method in to the execution stack such that when your method leaves, a block of code will run - even if the process terminates or an exception unwinds. In effect, it works like ensure: but at the 'Method' level instead of the block level. Or put another way - ensure: is used to empower the sender, BeforeYouLeave is used to empower the sent.
How do you use it? Actually it's stupidly easy:
thisContext onExitDo: [ my block of code to run when this method exits ]
The nice thing about this approach is that you can make your own protocols that use this, simply by calling it on different thisContext's - in fact, due to a good idea by Travis Griggs, you can also set up a block of code to run when a Process ends (or terminates).
Processor activeProcess onExitDo: [ my block of code to run when this process ends ]
So thanks to David Price, Travis Griggs and Terry Raymond for their input / help on this fun little goodie. It's in public store - so enjoy.