← Back to Lua Course | Chapter 5: Functions | Lesson 7 of 7

Error handling with pcall

pcall runs code safely and hands you the error instead of crashing the program.

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

lua
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
Common Mistakes
  1. Forgetting that pcall returns true or false first
  2. Ignoring the status and using the error as a result
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.