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.
Lua already has the necessary mechanisms to do something not entirely unlike exceptions. Namely
pcall.You can use
pcallto execute any Lua function. If that function (or any function it calls) callserror(assertcallserrorif the assertion condition is not true), then flow control will return to the site of thepcallstatement. Thepcallwill return false and an error message (what is passed toerror).With this, you can “throw” errors and “catch” them. Your “try” is just the
pcall; your “catch” statement is what checks thepcallresult.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.