Functions signal problems by raising errors, and callers catch them with try/except blocks. When you want errors as values instead of exceptions, there is also Result[T, E] with Ok and Err variants.
def divide(a: Int, b: Int) -> Int {
if b == 0 {
raise ValueError("division by zero")
}
return a // b
}
try {
let result = divide(10, 0)
} except ValueError as e {
print("Bad value")
} except Error as e {
print("Some other error")
} finally {
print("Always runs")
}
except Error: is the broadest catch. Bare except: is not supported. You can raise a string directly: raise "message" wraps it in RuntimeError.
| Type | Use case |
|---|---|
Error | Base of all Vary errors |
RuntimeError | General runtime errors |
TypeError | Type mismatches |
ValueError | Invalid values |
IOError | I/O failures |
KeyError | Missing dictionary keys |
IndexError | Out-of-bounds access |
ContractViolation | Failed precondition or postcondition |
ProcessError | Subprocess execution failure (not found, permission denied, timeout) |
TimeoutError | Task group exceeded its timeout |
Result[T, E] represents success or failure without exceptions:
def divide(a: Int, b: Int) -> Result[Int, Str] {
if b == 0 {
return Err("division by zero")
}
return Ok(a // b)
}
let r = divide(10, 3)
assert r.is_ok()
assert r.unwrap() == 3
| Method | Returns | Description |
|---|---|---|
.is_ok() | Bool | True if Ok |
.is_err() | Bool | True if Err |
.unwrap() | T | Unwrap Ok value (panics on Err) |
.unwrap_err() | E | Unwrap Err value (panics on Ok) |
.unwrap_or(default) | T | Unwrap Ok, or return default |
Match on Result with case Ok(value) and case Err(error).
? operatorThe ? postfix operator unwraps Ok or returns Err early:
def process() -> Result[None, FsError] {
let wp = WritePath.of("/tmp/out.txt")?
let _w = fs.write_text(wp, "hello")?
return Ok(None)
}
The enclosing function must return a Result with the same error type.
?else return operatorWhen unwrapping a Result or optional, ?else return provides a default value and exits the function early if the unwrap fails:
def get_name(id: Int) -> Str {
let user = find_user(id) ?else return "unknown"
return user.name
}
This is useful when the enclosing function does not return a Result and you want a fallback instead of propagating the error.
?else return also works on a plain optional (T?), and ?: accepts an exit as its right side: return, raise, break or continue.
def first_positive(xs: List[Int?]) -> Int {
for x in xs {
let n = x ?: continue
if n > 0 {
return n
}
}
return 0
}
let ... elseWhen several dependent lookups share one failure path, use let ... else. Clauses run left to right, a later clause can use names bound by an earlier one, and a clause without a name is a plain Bool condition. If any clause fails (a None value or a False condition), the single else block runs.
def set_room(c: Ctx, scope: Scope) -> Result[Room, Redirect] {
let user = c.user else {
return Err(Redirect("/login", None))
}
let id = integer_cast(c.param_str("room_id") ?: c.param_str("id")),
room = c.room_for_user(user.id, id),
scope.includes(room) else {
return Err(Redirect("/", "Room not found or inaccessible"))
}
return Ok(room)
}
The rules:
| Rule | Detail |
|---|---|
| Bound names are narrowed | Each bound name has the non-null type for the rest of the block. |
The else block must exit | It must not fall through. End it with return, raise, break, continue or a call to a function that returns Never. |
Bound names are not visible in else | Names bound by the clauses are not in scope inside the else block. |
| Clause types | A binding clause needs an optional value. A bare clause needs a Bool. |
An optional has map, and_then and filter. The function is not called when the value is None.
let name_len = find_user(id).map(lambda u: User: len(u.name))
let parsed = raw.and_then(lambda s: Str: parse_id(s))
let adult = find_user(id).filter(lambda u: User: u.age >= 18)
map returns U?, and_then takes a function that returns U?, and filter returns the same optional type.
NeverA function declared -> Never cannot return normally: every path must end in raise or a call to another Never function. A call to it ends the block, so the checker treats the code after it as unreachable and the call satisfies "all paths return".
def redirect_to(path: Str) -> Never {
raise Redirect(path)
}
def room_or_redirect(room: Room?) -> Room {
if room is None {
redirect_to("/")
}
return room
}