Lua Intermediate: OOP, Closures & Patterns

Lesson 4 of 5

Error Handling: pcall, xpcall, and error

Lua doesn't have try/catch, instead errors are handled with the built-in functions pcall, xpcall, error, and assert.

Raising errors

Lua

Calling error(message) immediately stops execution and unwinds the call stack, exactly like throw in other languages, except the "catch" is a separate function call rather than a block.

Catching errors with pcall

Lua

pcall ("protected call") runs a function and catches any error it raises. It always returns a boolean first (true if no error, false if one occurred), followed by either the function's return value(s), or the error message.

assert: a shortcut for a common check

Lua

assert(condition, message) is sugar for "if condition is falsy, error(message)", used constantly to validate function arguments up front.

xpcall: catching errors with a custom handler

Lua

xpcall is like pcall but takes a second argument, a message handler that runs while the stack is still unwound (useful for attaching a stack trace, or normalizing non-string error values like the table above).

TIP

Reach for assert for "this should never happen if the caller used the API correctly" checks, and reserve error + pcall for situations the caller is expected to actually handle, like a failed network request or invalid user input.

📝 Error Handling Quiz

Passing score: 70%
  1. 1.What does pcall return first, before any of the wrapped function's own results?

  2. 2.In Lua, error() can only be called with a string message.

  3. 3.____(condition, message) raises an error with the given message if condition is falsy.