lua以xpcall实现try/catch功能

本文介绍了如何在Lua中利用xpcall函数来实现类似try/catch的异常处理机制。通过示例展示了当尝试执行的代码块发生错误时,如何捕获并处理错误。在示例中,由于尝试concatenate一个nil值导致了错误,xpcall能够提供详细的错误堆栈跟踪信息,帮助定位问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-- 打印错误信息
local function __TRACKBACK__(errmsg)
    local track_text = debug.traceback(tostring(errmsg), 6);
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    print(track_text, "LUA ERROR");
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    local exception_text = "LUA EXCEPTION\n" .. track_text;
    return false;
end

--[[ 尝试调一个function 这个function可以带可变参数
如果被调用的函数有异常 返回false,退出此方法继续执行其他代码并打印出异常信息;]]
function trycall(func, ...)
    local args = { ... };
    return xpcall(function() func(unpack(args)) end, __TRACKBACK__);
end
--测试代码:

trycall(function(param)
      print("message "..param)
      print("message "..nil)
        end, "test trycall")


##输出结果如下:

>lua -e "io.stdout:setvbuf 'no'" "itertor_test.lua"  message test trycall ---------------------------------------- TRACKBACK ---------------------------------------- itertor_test.lua:45: attempt to concatenate a nil value stack traceback: itertor_test.lua:43: in main chunk [C]: ? LUA ERROR ---------------------------------------- TRACKBACK ---------------------------------------- >Exit code: 0


xpcall (f, err)

This function is similar to pcall,except that you can set a new error handler.

xpcall calls function f in protected mode,using err as the error handler.Any error inside f is not propagated;instead, xpcall catches the error,calls the err function with the original error object,and returns a status code.Its first result is the status code (a boolean),which is true if the call succeeds without errors.In this case, xpcall also returns all results from the call,after this first result.In case of any error,xpcall returns false plus the result from err.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值