Error handling with pcall
pcall runs code safely and hands you the error instead of crashing the program.
In this page:
Error handling with pcall
The function error(msg) raises an error and assert(cond, msg) raises one when cond is falsy. pcall(f, ...) calls f in protected mode and returns true plus the results, or false plus the error value. Errors can be any value, including tables, and error with a string adds the position unless you pass level 0.
Note:
Use xpcall with debug.traceback as handler when you need a stack trace.
Example: Error handling with pcall
print(pcall(function() return "fine", 2 end))
local ok, err = pcall(function() error("boom", 0) end)
print(ok, err)
local ok3, e3 = pcall(error, {code = 42})
print(ok3, e3.code)
local ok2, e2 = pcall(function() local x = nil; return x.field end)
print(ok2, type(e2))
print(pcall(assert, false, "assertion msg"))
print(select(2, pcall(assert, 1 == 1, "unused")))
-- Output:
-- true fine 2
-- false boom
-- false 42
-- false string
-- false assertion msg
-- true unused
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that pcall returns true or false first
- Ignoring the status and using the error as a result
- Expecting error messages to never include file and line information
Chapter Summary
- error raises an error
- assert checks a condition
- pcall returns a status then results
- Errors may be any value
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: