🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Error Handling

Error handling is how a program catches a failure and reports it without losing control. Lua raises a failure with error() and catches one with pcall().

pcall catches a failure

The check function calls error() on line 2 when the value is negative. pcall() turns that stop into two printable values.

local function check(n)
  if n < 0 then error("negative value") end
  return n
end
local ok, msg = pcall(check, -1)
print(ok, msg)

pcall passes a success through

The double function runs cleanly here. pcall() reports true and hands back the return value.

local function double(n)
  return n * 2
end
local ok, result = pcall(double, 21)
print(ok, result)

One function, one good call and one bad call

The divide function calls error() on line 2 when the divisor is zero. The first call succeeds and the second is caught.

local function divide(a, b)
  if b == 0 then error("divide by zero") end
  return a / b
end
local ok1, r1 = pcall(divide, 10, 2)
print(ok1, r1)
local ok2, msg = pcall(divide, 10, 0)
print(ok2, msg)

Example

local function divide(a, b)
  if b == 0 then error("divide by zero") end
  return a / b
end
print(pcall(divide, 12, 3))
print(pcall(divide, 10, 0))
print(pcall(divide, 7, 2))

Key points

  • error(): stops the running function and carries a message with it.
  • Message text: the message should say plainly what went wrong.
  • pcall(): runs a function in a protected way and reports how it ended.
  • Success: pcall() returns true first, followed by the results of the function.
  • Failure: pcall() returns false first, followed by the error message.
  • Message form: an error message names the file and the line of the error() call.

In this example, a small calculator divides through pcall() three times. The first call prints true and 4.0. The second call divides by zero, so it prints false and the message from line 2. The third call succeeds again and prints true and 3.5, and the program never stopped.

Note

a bare error() stops the whole program, so this lesson only shows messages through pcall().

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does pcall() return when the function it runs fails?