Lesson 50 of 55
9 mins readPython Error Handling: error, assert & Protected Calls (pcall)
In Plain English
Lua uses `error(msg)` and `assert(cond, msg)` to raise exceptions. Catch and handle errors safely in protected mode using `pcall(func, args)` or `xpcall` with a traceback error handler.
Deep Dive: How It Works
error(msg): Raises a runtime error, aborting execution if unhandled.
assert(cond, msg): If `cond` is false/nil, raises error with `msg`; otherwise returns `cond`.
pcall(fn, ...): Executes `fn` in protected mode. Returns `true, results...` on success, or `false, err_msg` on error.
xpcall(fn, err_handler): Catches error and passes it through an error handler (e.g. `debug.traceback`).
Core Rules to Remember

Protected Calls (pcall): Guarantees the application will not crash on invalid inputs or exceptions.

Status Bool First Return: `local ok, res = pcall(...)` returns true on success, false on failure.
Live Interactive Example
Hit Run Code to see it liveSafe Division with pcall and error
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: pcall intercepted the error without terminating the Lua process.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Safely Execute Failing Function with pcall
Call `pcall(function() error("Service Down") end)`.
If `not ok`, print `"Handled failure: " .. err:match("([^
]+)")`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.