Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 816
Ian Boyd Avatar asked Jan 02 '12 02:01

Ian Boyd


People also ask

Is there a try except in C?

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.

Does C language have try-catch?

Try-Catch mechanisms are common in many programming languages such as Python, C++, and JavaScript.

What is Lua Pcall?

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 .

What is the difference between try-catch block and try finally block?

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.


1 Answers

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.

like image 187
Nicol Bolas Avatar answered Oct 11 '22 06:10

Nicol Bolas