Protected Calls with pcall
Catch errors safely using pcall and interpret return values.
pcall Basics
pcall(f, ...) calls function f with arguments ... in protected mode. If f succeeds, pcall returns true followed by all return values. If f errors, pcall returns false followed by the error message. The program continues either way.
local function risky(x)
if x < 0 then error("negative input: " .. x) end
return math.sqrt(x)
end
local ok, result = pcall(risky, 9)
print(ok, result) -- true 3.0
ok, result = pcall(risky, -1)
print(ok, result) -- false ...: negative input: -1Catching Specific Errors
Check the error value type after pcall to handle different error kinds differently. Table errors have structured data; string errors have a message. Always handle both cases.
local function op(errType)
if errType == "table" then
error({code=42, msg="structured error"})
else
error("plain string error")
end
end
local ok, err = pcall(op, "table")
if not ok then
if type(err) == "table" then
print("Code:", err.code, "Msg:", err.msg)
else
print("String error:", err)
end
endAll lessons in this course
- The error() Function
- Protected Calls with pcall
- xpcall and Message Handlers
- Structured Error Objects