Language

Error handling

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.

Try / except / finally

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.

Error types

TypeUse case
ErrorBase of all Vary errors
RuntimeErrorGeneral runtime errors
TypeErrorType mismatches
ValueErrorInvalid values
IOErrorI/O failures
KeyErrorMissing dictionary keys
IndexErrorOut-of-bounds access
ContractViolationFailed precondition or postcondition
ProcessErrorSubprocess execution failure (not found, permission denied, timeout)
TimeoutErrorTask group exceeded its timeout

Result type

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
MethodReturnsDescription
.is_ok()BoolTrue if Ok
.is_err()BoolTrue if Err
.unwrap()TUnwrap Ok value (panics on Err)
.unwrap_err()EUnwrap Err value (panics on Ok)
.unwrap_or(default)TUnwrap Ok, or return default

Match on Result with case Ok(value) and case Err(error).

The ? operator

The ? 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.

The ?else return operator

When 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 ... else

When 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:

RuleDetail
Bound names are narrowedEach bound name has the non-null type for the rest of the block.
The else block must exitIt 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 elseNames bound by the clauses are not in scope inside the else block.
Clause typesA binding clause needs an optional value. A bare clause needs a Bool.

Optional combinators

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.

Never

A 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
}
← Collections and strings
Readable blocks →