如何在没有 try-finally 或 try- except 的语言中模拟它们

发布于 2024-12-23 17:13:12 字数 368 浏览 1 评论 0原文

是否有任何方法可以在没有它们的语言中模拟try-finallytry- except

如果发生一些随机的、不可预测的异常,我需要确保运行一些清理操作。

可以尝试确保没有抛出异常,这样我就可以确定我的清理代码始终运行 - 但这样我就不需要try-finally/ except

此刻我正在尝试在 Lua 中创建一个 try-finally ;但我认为任何解决方案也适用于其他语言。

尽管在我的一生中,我无法弄清楚如果没有语言基础设施提供的管道如何处理异常。

但问一下总没有坏处。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傲鸠 2024-12-30 17:13:12

Lua 已经拥有必要的机制来执行与异常类似的操作。即pcall

您可以使用pcall来执行任何Lua函数。如果该函数(或其调用的任何函数)调用error(如果断言条件不为真,则assert调用error),那么流程控制将返回到pcall 语句的位置。 pcall 将返回 false 和一条错误消息(传递给 error 的内容)。

有了这个,您可以“抛出”错误并“捕获”它们。你的“尝试”只是pcall;您的“catch”语句用于检查 pcall 结果。

另外,请记住:Lua 是一个垃圾收集环境。您不需要做任何清理工作。或者如果你这样做,你需要更改任何 Lua 模块需要的内容。 Lua API 应该是 Lua API,而不是 C 或 C++ API。

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.

以往的大感动 2024-12-30 17:13:12

从来没有用 lua 编程过(这就是你标记的)。但是,包括此在内的多个网页 http://jessewarden.com/2011 /01/lua-for-actionscript-developers.html提到受保护的调用(pcall)是lua错误处理装置。

希望这有帮助。

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.

柠檬心 2024-12-30 17:13:12

这个Lua异常处理系统怎么样?您还可以使用 Lua RAII 机制。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文