Error Handling in Depth
Clean Language has a direct, explicit error system. You signal errors with error() and handle them at the call site with onError. Errors are visible in the code — you decide exactly where they are caught and what the fallback is, with no hidden exception stacks.
Part of: How Clean works
Signal errors with error() and catch them with onError at the call site:
start:
number good = safe_divide(10.0, 2.0)
print("10 / 2 = " + good.toString())
number safe = safe_divide(10.0, 0.0) onError -1.0
print("10 / 0 = " + safe.toString() + " (used fallback)")
functions:
number safe_divide(number a, number b)
if b == 0.0
error("Division by zero")
return a / b10 / 2 = 5
10 / 0 = -1 (used fallback)error("message") signals an error from inside a function. At the call site, appending onError VALUE provides a fallback — if the function errors, you get the fallback value instead of crashing. Each call site decides its own fallback independently.
Chain validation and onError to build robust parsers:
start:
integer a = parse_age("28")
print("Valid: " + a.toString())
integer b = parse_age("") onError 0
print("Empty fallback: " + b.toString())
integer c = parse_age("abc") onError 0
print("Invalid fallback: " + c.toString())
functions:
integer parse_age(string input)
if input.length() == 0
error("Age cannot be empty")
integer age = input.toInteger() onError -1
if age < 0
error("Age must be positive")
if age > 150
error("Age is unrealistically high")
return ageValid: 28
Empty fallback: 0
Invalid fallback: 0onError can be used on any expression, including another onError result. input.toInteger() errors on non-numeric input, and onError -1 catches it; then if age < 0 signals a new error, caught by the caller. This chains validation naturally.
- error("message") signals an error — execution stops at that point in the function
- function() onError VALUE provides a fallback if the function signals an error
- onError is local — each call site decides its own fallback independently
- Chain onError: toInteger() onError -1 converts parse failures to a sentinel value