How to simulate try-finally or try-except in languages that don't have them

Ian Boyd picture Ian Boyd · Jan 2, 2012 · Viewed 8.3k times · Source

Is there any way to simulate a try-finally or try-except in a language that doesn't have them?

If there's some random, unpredictable, exception happens i need to be sure some cleanup runs.

i could try to be sure that no exception in thrown, that way i am sure my cleanup code always runs - but then i wouldn't need the try-finally/except.

Right this moment i'm trying to create a try-finally in Lua; but i think any solution would work in other languages as well.

Although, for the life of me, i cannot figure out how an exception can be handled without the plumbing provided by the language infrastructure.

But never hurts to ask.

Answer

Nicol Bolas picture Nicol Bolas · Jan 2, 2012

Lua already has the necessary mechanisms to do something not entirely unlike exceptions. Namely pcall.

You can use pcall to execute any Lua function. If that function (or any function it calls) calls error (assert calls error if the assertion condition is not true), then flow control will return to the site of the pcall statement. The pcall will return false and an error message (what is passed to error).

With this, you can "throw" errors and "catch" them. Your "try" is just the pcall; your "catch" statement is what checks the pcall result.

Also, remember: Lua is a garbage collected environment. You shouldn't need to do any cleanup work. Or if you do, you need to change whatever Lua module requires it. Lua APIs should be Lua APIs, not C or C++ APIs.