Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 32 ยท Errors, Modules and Coroutines

Error Handling

Learn how Lua raises and catches errors with error, assert, pcall and xpcall, how to throw tables as error objects, read tracebacks and clean up with to-be-closed variables.

Every program meets problems it did not plan for: a file is missing, a user types letters where a number belongs, a table you expected is nil. Lua has no try and catch keywords. Instead it gives you a small set of functions: error raises a problem, pcall and xpcall catch it, and assert is a shortcut for "stop if this is not true".

In this lesson you will learn the difference between errors you raise on purpose and errors Lua raises for you, how to catch both, how to carry structured information in an error object, how to read a traceback, and how Lua 5.4 cleans up resources with to-be-closed variables. If you are not yet comfortable with functions, read Functions first.

Lua is not installed on this site. The Lua code below is read-only, and the outputs shown are what the real interpreter prints (the file name in messages depends on how you run your script). The runnable examples are JavaScript stand-ins that model the same ideas with try and catch.

Three ways a function can fail

error() Stops the current call and unwinds the stack.
nil, message Return the failure and let the caller decide.
assert() Raise an error unless a value is truthy.

Use returns for expected failures and error for bugs and broken promises.

1 / 2

Raising an error with error

error(message) stops the running function and unwinds the call stack until someone catches the error. If nobody does, the standalone lua program prints the message and a traceback and exits.

When the message is a string, error adds the position where it was called, in the form file:line:. That is why error messages look like main.lua:3: division by zero.

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

print(pcall(divide, 10, 2))
print(pcall(divide, 1, 0))
TEXT
true	5.0
false	main.lua:3: division by zero

pcall(f, ...) calls f in protected mode. It never raises: it returns true followed by the function's results when everything worked, or false followed by the error value when something failed. Note that 10 / 2 is 5.0, because / always gives a float in Lua 5.4.

The level argument

The second argument of error controls which position is added. Level 1 (the default) is the line that called error. Level 2 blames the caller of your function, which is the right choice for argument checks, because the mistake is in the code that passed a bad value. Level 0 adds no position at all.

LUA
local function check(n)
  if type(n) ~= "number" then
    error("expected a number", 2)
  end
  return n
end

local function use()
  local v = check("x")
  return v
end

print(pcall(use))
TEXT
false	main.lua:9: expected a number

Line 9 is the check("x") call inside use, not the error line inside check. (The call is deliberately not written as return check("x"): a tail call replaces the caller's stack frame, so level 2 would point somewhere less useful.)

Errors Lua raises for you

You do not have to call error to get an error. Lua raises one whenever an operation makes no sense:

LUA
local config = nil
print(pcall(function() return config.name end))
print(pcall(function() return 1 + {} end))
print(pcall(function() local f; f() end))

The messages name the problem and, when Lua can tell, the variable involved, for example attempt to index a nil value (upvalue 'config'), attempt to perform arithmetic on a table value and attempt to call a nil value (local 'f'). These are by far the most common errors you will read as a beginner. Almost all of them mean "a variable was nil when you expected something else", so look at where that variable was set.

assert: check and raise in one line

assert(v, message) returns all its arguments if v is truthy, and raises message as an error if v is nil or false. Without a message the error text is assertion failed!. Because many Lua functions return nil, errmessage on failure, assert fits them perfectly:

LUA
local n = assert(tonumber("42"))            -- 42
local f = assert(io.open("settings.txt"))   -- raises if the file is missing

If the file does not exist, the second line raises the message from io.open, which looks like settings.txt: No such file or directory. Two details are worth remembering. The message of assert is not given a position prefix, and it is evaluated even when the assertion passes, so avoid building expensive messages inside the call.

Return values or errors?

A good rule: use return values for failures the caller should expect (a file might not exist, input might be invalid), and use error for situations that are bugs or broken contracts (a function got a table where a number is required). The first style looks like this:

LUA
local function parseAge(text)
  local n = tonumber(text)
  if not n then
    return nil, "not a number: " .. tostring(text)
  end
  if n < 0 then
    return nil, "age cannot be negative"
  end
  return n
end

Callers check the first result, and can turn the failure into an error with assert(parseAge(input)) when they do not want to handle it.

JS pcall and error, modelled in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Error objects: throwing tables

An error value does not have to be a string. Any Lua value can be thrown, and pcall hands it back unchanged. Tables are the practical choice, because they can carry a code, a message and any other details, and the caller can inspect fields instead of parsing text.

LUA
local function fail(code, message)
  error({code = code, message = message})
end

local ok, err = pcall(fail, 404, "page not found")
print(ok, err.code, err.message)
TEXT
false	404	page not found

A table error gets no position prefix, so add a where field yourself if you want one. Give the table a metatable with __tostring to get readable output if the error ever escapes to the top level; without it the standalone interpreter prints only (error object is a table value). See Metatables and Metamethods for how __tostring works.

JS Errors as objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

xpcall and tracebacks

pcall returns the error value, but by the time you have it the stack has already unwound, so you cannot see how the program got there. xpcall(f, handler, ...) fixes that: the message handler runs at the point of the error, before unwinding, and whatever it returns becomes the second result of xpcall. The standard handler is debug.traceback, which appends a stack listing to the message:

LUA
local function inner() error("deep problem") end
local function outer() inner() end

local ok, report = xpcall(outer, debug.traceback)
print(ok)
print(report)

The first line printed is false. The report starts with main.lua:1: deep problem, followed by stack traceback: and one line per active function, innermost first. The exact lines depend on your script, so treat them as a diagnostic for humans rather than something to parse.

A custom handler is an ordinary function that receives the error value:

LUA
local function handler(err)
  return debug.traceback("handled: " .. tostring(err), 2)
end

Keep handlers short and simple. If the handler itself fails, Lua reports an error in the error handler, which hides the original problem.

To-be-closed variables (Lua 5.4)

Resources such as files and locks must be released even when an error flies past. Lua 5.4 adds the attribute <close> for local variables. When the variable goes out of scope, by reaching end, by break, return or goto, or by an error, Lua calls its __close metamethod with the value and the error object (or nil when there was no error).

LUA
local function resource(name)
  return setmetatable({}, {__close = function(_, err)
    print("closing " .. name, err)
  end})
end

do
  local a <close> = resource("a")
  local b <close> = resource("b")
  print("working")
end

print(pcall(function()
  local r <close> = resource("r")
  error("boom", 0)
end))
TEXT
working
closing b	nil
closing a	nil
closing r	boom
false	boom

Variables close in reverse order of declaration, like a stack. The value must have a __close metamethod (or be nil or false, which are ignored), otherwise Lua raises an error when the variable is declared. File handles from io.open support <close> in Lua 5.4, which gives you automatic closing without a pcall.

JS Cleanup order with finally

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Catching too much. Wrapping a whole program in pcall and printing ok hides bugs. Catch errors where you can do something useful about them.
  • Forgetting that pcall takes the function, not its call. Write pcall(f, 1) or pcall(function() return f(1) end), never pcall(f(1)), which runs f(1) first, outside the protection.
  • Comparing message text. Messages include file names and line numbers and change when code moves. Use table error objects with a code field when callers need to branch.
  • Ignoring the first result. local result = pcall(f) stores true or false, not the result.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pcall(error, "x", 0) return?

    pcall never raises. error throws the string unchanged because level 0 adds no position, and pcall returns false followed by the error value.
  2. 2. Which call blames the caller of your function for a bad argument?

    Level 2 adds the position of the code that called your function. Level 1 points at the error call itself, level 0 adds nothing, and assert never adds a position.
  3. 3. What is the main advantage of xpcall over pcall?

    The message handler sees the live stack, so debug.traceback can report how the program reached the error. Both functions catch the same errors.
  4. 4. In what order do <close> variables in the same block get closed?

    The most recently declared variable is closed first, so resources are released like a stack.
  5. 5. Why throw a table instead of a string?

    Any value can be an error. A table can carry a code and details that callers inspect directly.

Summary

  • error(value, level) raises an error; string messages get a file:line: prefix, controlled by level.
  • pcall(f, ...) returns true, results... or false, errorValue and never raises.
  • assert(v, msg) returns its arguments when v is truthy and raises msg otherwise.
  • Return nil, message for expected failures and raise errors for bugs.
  • Error values can be tables with a code and details.
  • xpcall(f, debug.traceback) gives you a stack traceback at the point of the error.
  • local x <close> (Lua 5.4) runs __close when the scope ends, even after an error.

Next, learn how to split a program into files in Modules and require.