0Pricing
Lua Academy · Lesson

The error() Function

Raise errors with error() and understand error levels and messages.

Raising Errors

error(message, level) raises a Lua error. Execution stops and the error propagates up the call stack until caught by pcall or xpcall, or until it terminates the program. The message can be any value — string, table, number.

local function divide(a, b)
  if b == 0 then
    error("division by zero")
  end
  return a / b
end

print(divide(10, 2))    -- 5.0
-- divide(10, 0)        -- ERROR: division by zero

Error Levels

The second argument to error() controls where the error is reported. Level 1 (default) points to the error() call itself. Level 2 points to the caller. Level 0 adds no position info. Use level 2 in library functions to blame the user's code.

local function assertPositive(n, name)
  if n <= 0 then
    error((name or "value") .. " must be positive, got " .. n, 2)
    -- level 2: blame the caller, not this function
  end
  return n
end

local function compute(x)
  assertPositive(x, "x")   -- error points here if x <= 0
  return math.sqrt(x)
end

compute(-5)  -- error: "x must be positive, got -5" at compute() call

All lessons in this course

  1. The error() Function
  2. Protected Calls with pcall
  3. xpcall and Message Handlers
  4. Structured Error Objects
← Back to Lua Academy