Error Handling — try/catch
Larz covers how Larzscript handles things going wrong: wrapping risky code in try/catch, and require - the money-native guardrail keyword that throws its own error when a condition isn't met.
try and catch
Wrap risky code in try. If it throws, catch runs instead of crashing the program - the caught error is a dict with type and message:
let nums = [1, 2, 3]
try {
print(nums[10])
} catch e {
print("caught:", e["type"])
print("message:", e["message"])
}
print("still running")Output
caught: LarzRuntimeError message: index 10 out of range (length 3) (line 3) still running
require — the money-native guardrail
require checks a condition and throws if it's false - a guardrail you write yourself. Pair it with try/catch for real validation:
fn withdraw(balance, amount) {
require amount <= balance, "insufficient funds"
return balance - amount
}
try {
print(withdraw(100, 500))
} catch e {
print("blocked:", e["message"])
}
print(withdraw(100, 40))Output
blocked: insufficient funds (line 2) 60
Every snippet on this page is run through the real larzscript interpreter, not hand-typed — what you see in the Output blocks is the actual output, for everything shown: a caught runtime error and a caught require failure.
Related
LarzBank — A Real Bank, Built in LarzscriptSee wallet, pay and require composed into a real, open-source app.→Lesson 9: Money-Native Basicswallet, price, pay - what's next after try/catch and require.→Lesson 7: Modules & the Package Ecosystemimport, alias, and call through it - the functions this lesson wraps in try/catch.→Lesson 4: Functions & Recursionfn and return - require and try/catch both live inside functions exactly like these.→What Is Larzscript?The full explainer on the money-native pitch, including require, wallet and pay.→Learn Larzscript Cookbook29 short "how to X in Larzscript" recipes, several using require as a real guardrail.→