How to simulate try-finally or try-except, except for languages ​​in which they are not

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

If a random, unpredictable exception occurs, I must be sure that some cleanup is being done.

I could be sure that there was no exception in the throw, so I am sure that my cleanup code always runs - but then I will not need try-finally/except .

At this point, I am trying to create try-finally in Lua; but I think that any solution will work in other languages.

Although, for my life, I can’t understand how an exception can be handled without the plumbing provided by the language infrastructure.

But it never hurts to ask.

+6
source share
4 answers

Lua already has the necessary mechanisms to do something completely different from exceptions. Namely pcall .

You can use pcall to execute any Lua function. If this function (or any function it calls) calls error ( assert calls error if the assertion condition is incorrect) then flow control will return to the pcall statement pcall . pcall will return false and an error message (which is passed error ).

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

Also, remember: Lua is garbage collection. You do not need to perform any cleaning operations. Or, if you do, you need to modify any Lua module. Lua APIs must be Lua APIs, not C or C ++ APIs.

+16
source

It has never been programmed in lua (this is what you noted as). However, several web pages, including this http://jessewarden.com/2011/01/lua-for-actionscript-developers.html , have noted that a secure call (pcall) is a lua error handling device.

Hope this helps.

+2
source

In general, exceptions can be caught using the signal () function. Not sure if lua will support this. In C, this is what you will use. And this is a big annoyance! (somewhat complicated.)

0
source

What about the Lua Exception Handling system ? You can also use Lua RAII mechanisms.

0
source

Source: https://habr.com/ru/post/904872/


All Articles