This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


8.4 – Error Handling and Exceptions

For many applications, you do not need to do any error handling in Lua. Usually, the application program does this handling. All Lua activities start from a call by the application, usually asking Lua to run a chunk. If there is any error, this call returns an error code and the application can take appropriate actions. In the case of the stand-alone interpreter, its main loop just prints the error message and continues showing the prompt and running the commands.

If you need to handle errors in Lua, you should use the pcall function (protected call) to encapsulate your code.

Suppose you want to run a piece of Lua code and to catch any error raised while running that code. Your first step is to encapsulate that piece of code in a function; let us call it foo:

    function foo ()
        ...
      if unexpected_condition then error() end
        ...
      print(a[i])    -- potential error: `a' may not be a table
        ...
    end
Then, you call foo with pcall:
    if pcall(foo) then
      -- no errors while running `foo'
      ...
    else
      -- `foo' raised an error: take appropriate actions
      ...
    end
Of course, you can call pcall with an anonymous function:
    if pcall(function () ... end) then ...
    else ...

The pcall function calls its first argument in protected mode, so that it catches any errors while the function is running. If there are no errors, pcall returns true, plus any values returned by the call. Otherwise, it returns false, plus the error message.

Despite its name, the error message does not have to be a string. Any Lua value that you pass to error will be returned by pcall:

    local status, err = pcall(function () error({code=121}) end)
    print(err.code)  -->  121
These mechanisms provide all we need to do exception handling in Lua. We throw an exception with error and catch it with pcall. The error message identifies the kind or error.