如何在没有 try-finally 或 try- except 的语言中模拟它们
是否有任何方法可以在没有它们的语言中模拟try-finally
或try- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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) callserror
(assert
callserror
if the assertion condition is not true), then flow control will return to the site of thepcall
statement. Thepcall
will return false and an error message (what is passed toerror
).With this, you can "throw" errors and "catch" them. Your "try" is just the
pcall
; your "catch" statement is what checks thepcall
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.
从来没有用 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.
这个Lua异常处理系统怎么样?您还可以使用 Lua RAII 机制。
How about this Lua Exception Handling system? You can also use Lua RAII mechanisms.