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.
The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.
Try-Catch mechanisms are common in many programming languages such as Python, C++, and JavaScript.
Lua Error Handling Using pcall pcall stands for "protected call". It is used to add error handling to functions. pcall works similar as try-catch in other languages. The advantage of pcall is that the whole execution of the script is not being interrupted if errors occur in functions called with pcall .
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With