سؤال

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 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.

نصائح أخرى

Never programmed in lua (which is what you have this tagged as). However, several web pages including this one http://jessewarden.com/2011/01/lua-for-actionscript-developers.html mentioned that protected call (pcall) is lua error handling device.

Hope this helps.

In general, exceptions can be caught using the signal() function. Not sure that lua would support such though. In C, that's what you'd use. And that's a big annoyance! (somewhat complicated.)

How about this Lua Exception Handling system? You can also use Lua RAII mechanisms.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top