Skip to content
Lua

Error Handling (pcall)

Protected calls and error handling in Lua.

By EZ4Code Team
errorpcallexception

Code

-- Function that may error
local function risky(x)
  if x < 0 then
    error("negative input: " .. x, 2)  -- 2 = report caller's line
  end
  return math.sqrt(x)
end

-- pcall: protected call (catches errors)
local ok, result = pcall(risky, -5)
if ok then
  print("Result:", result)
else
  print("Error:", result)  -- result is the error message
end

-- With traceback
local ok2, err = pcall(function()
  error("custom error")
end)
if not ok2 then
  print(debug.traceback(err, 2))
end

-- xpcall: with custom error handler
local function handler(err)
  return "Handled: " .. tostring(err) .. "\n" .. debug.traceback()
end

local ok3, result3 = xpcall(function()
  return risky(-1)
end, handler)

-- assert (throws if false/nil)
local function load_config(path)
  local f = assert(io.open(path, "r"), "Cannot open: " .. path)
  return f:read("*a")
end

Explanation

pcall wraps a call — returns (true, result) on success or (false, err) on error. error(msg, level) throws — level 0 omits position, 1 (default) is the error line, 2 is the caller's line. xpcall adds a handler for custom formatting/traceback. debug.traceback returns the stack. assert(value, msg) throws if value is nil/false — common for checking io.open results.

More Lua Snippets