Panic in Lua

Our program demonstrates how to handle exceptional situations in Lua. While Lua doesn’t have a built-in panic function like some other languages, we can simulate similar behavior using error handling and the error function.

local function main()
    -- We'll use error() throughout this site to check for
    -- unexpected errors. This is the only program on the
    -- site designed to raise an error.
    error("a problem")

    -- A common use of error is to abort if a function
    -- returns an error value that we don't know how to
    -- (or want to) handle. Here's an example of
    -- raising an error if we get an unexpected error when creating a new file.
    local file, err = io.open("/tmp/file", "w")
    if not file then
        error(err)
    end
end

-- Wrap the main function in pcall to catch any errors
local status, err = pcall(main)
if not status then
    print("Error occurred: " .. err)
    os.exit(1)
end

Running this program will cause it to raise an error, print an error message, and exit with a non-zero status.

When the first error() in main is called, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first error() call.

$ lua panic.lua
Error occurred: panic.lua:6: a problem

Note that unlike some languages which use exceptions for handling of many errors, in Lua it is idiomatic to use multiple return values to indicate errors, with the first return value typically being nil or false in case of an error, and the second value being the error message.

The pcall function (protected call) is used to catch any errors that might occur during the execution of a function. It’s similar to a try-catch block in other languages.