Codectionary / Developer documentation / Luau

Handling errors with pcall and xpcall

Protected calls turn an exception into a success flag and a result. They are useful around operations that can fail outside your control. They do not repair bad state, retry automatically, or mean every error should be ignored.

Syntax

local ok, result = pcall(function()
    return riskyOperation()
end)

Examples

Separate failure from an ordinary result

Standalone Luau or a Script in ServerScriptService. The invalid input raises an error; pcall returns false and that error value. The calculation does not continue past error.

local function divide(a: number, b: number): number
    if b == 0 then error("Divisor must not be zero") end
    return a / b
end
local ok, result = pcall(divide, 8, 0)
if ok then
    print(result)
else
    print("Calculation failed:", result)
end

Attach diagnostic context

Roblox Studio Script in ServerScriptService. The xpcall handler adds a traceback for debugging. Keep the handler non-yielding and do not show internal diagnostics directly to players.

local ok, detail = xpcall(function()
    error("Lesson configuration missing")
end, function(message)
    return debug.traceback(tostring(message), 2)
end)
if not ok then
    warn(detail)
end

Best practices

  • Check the success flag before using the result; an error string is not loaded player data.
  • Keep protected regions narrow so the failure source remains clear.
  • Retry only transient operations and use bounded attempts; programming errors need fixes, not endless retries.

At a glance

Purpose
Typed scripting and Roblox development
File extension
.luau
Runs in
Luau host; Roblox engine examples require Roblox Studio
Usually used with
Roblox APIs and Studio

Specifications & further reading

Related Luau documentation