Lua 高级教程——错误处理(pcall/xpcall)
Lua 用 pcall(保护调用) 捕获运行时错误,避免程序崩溃。1. pcall 基础
local function div(a,b)
if b==0 then error("除数不能为0") end
return a/b
end
local ok, res = pcall(div, 10, 0)
if ok then
print("结果:", res)
else
print("错误:", res)-- 错误:除数不能为0
end2. xpcall(带错误处理函数)
local function errHandler(err)
return "捕获错误:"..err
end
local ok, res = xpcall(div, errHandler, 10, 0)
print(res)-- 捕获错误:除数不能为0
感谢分享,学习了! 很不错,感谢楼主分享,我学到了;P
页:
[1]