Handling Errors
Things go wrong. A user enters something unexpected, a calculation hits an impossible case, a resource isn't available. Clean Language gives you a clean, readable way to deal with it.
Part of: Install and setup
You raise an error with error(), and catch it with onError:
start:
integer result = divide(10, 2) onError -1
print(result.toString())
integer bad = divide(10, 0) onError -1
print(bad.toString())
functions:
integer divide(integer a, integer b)
if b == 0
error("Cannot divide by zero")
return a / b5
-1The onError -1 part means: if anything goes wrong, use -1 instead. No crash, no mystery — just a predictable fallback.
For more than just a fallback value, use onError: with a block:
start:
integer result = divide(10, 0) onError -1
print(result.toString())
integer other = divide(10, 0) onError:
print("Something went wrong: " + error)
print(other.toString())
functions:
integer divide(integer a, integer b)
if b == 0
error("Cannot divide by zero")
return a / b-1
Something went wrong: Cannot divide by zero
0onError: with a block runs every line in it when something fails, and error holds the message. The variable keeps its zero value (0 here), so use onError value when you need a specific fallback.
- Use error("message") inside a function to raise an error
- expression onError fallbackValue — catch and provide a simple fallback
- expression onError: with a block — run any code when it fails; error holds the message
- Errors propagate up the call chain until something catches them
- If nothing catches an error, the program stops with an error message