BudiBadu Logo
Samplebadu

Lua by Example: Error Handling

Lua 5.4

Lua uses `pcall` (protected call) to catch errors. This example shows how to raise errors and handle them gracefully.

Code

function dangerousDiv(a, b)
    if b == 0 then
        -- Raise an error
        error("Division by zero!")
    end
    return a / b
end

-- Protected call
-- Returns status (boolean) and result/error
local status, result = pcall(dangerousDiv, 10, 0)

if status then
    print("Success: " .. result)
else
    print("Caught error: " .. result)
end

-- xpcall allows a custom error handler
local function errorHandler(err)
    return "Debug Info: " .. err
end

status, result = xpcall(dangerousDiv, errorHandler, 10, 0)
print(result)

Explanation

Lua handles errors using the error() function to throw an exception and pcall() (protected call) to catch it. Unlike try-catch blocks in other languages, pcall is a function that takes the function to be called and its arguments. It returns true if the call succeeded, followed by the return values, or false if an error occurred, followed by the error message.

The error(message, [level]) function terminates the currently running function. The optional level argument controls where the error is reported to have occurred (current function, caller, etc.), which is useful when writing library functions that validate arguments.

For more advanced error handling, xpcall (extended protected call) accepts a message handler function. This handler is called before the stack unwinds, allowing you to inspect the stack trace using debug.traceback() or format the error message before it is returned.

Code Breakdown

3
error("...") aborts execution. It's similar to throw in Java/JS.
10
pcall(func, args...) calls the function in "protected mode". It prevents the program from crashing.