[Lua] try catch实现

时间:2023-03-08 22:21:35

参考了https://blog.****.net/waruqi/article/details/53649634这里的代码,但实际使用时还有些问题,修改后在此记录一下。

 -- 异常捕获
function try(block)
-- get the try function
local try = block[]
assert(try) -- get catch and finally functions
local funcs = block[] -- try to call it
local ok, errors = xpcall(try, debug.traceback)
if not ok then
-- run the catch function
if funcs and funcs.catch then
funcs.catch(errors)
end
end -- run the finally function
if funcs and funcs.finally then
funcs.finally(ok, errors)
end -- ok?
if ok then
return errors
end
end function test()
try
{
function ()
xxx()
end,
{
-- 发生异常后,被执行
catch = function (errors)
print("LUA Exception : " .. errors)
end, finally = function (ok, errors)
-- do sth.
print("finally can work")
end
},
}
print("I can print normally!")
end test()

异常捕获代码+测试代码

调用test()后,运行结果如下:

[Lua] try catch实现

又改了一版,格式输入看起来更容易理解,代码如下:

 -- 异常捕获
function try1(block)
local main = block.main
local catch = block.catch
local finally = block.finally assert(main) -- try to call it
local ok, errors = xpcall(main, debug.traceback)
if not ok then
-- run the catch function
if catch then
catch(errors)
end
end -- run the finally function
if finally then
finally(ok, errors)
end -- ok?
if ok then
return errors
end
end function test1()
try1{
main = function ()
xxx()
end,
catch = function (errors)
print("catch : " .. errors)
end,
finally = function (ok, errors)
print("finally : " .. tostring(ok))
end,
}
print("I can print normally!")
end test1()

新版try-catch

打印结果如下:

[Lua] try catch实现