Skip to content

Error Handling

Types are non-nullable by default in Writ. Use Optional<T> for values that may be absent, and Result<T> for operations that can fail.

Wrap in Optional<T> to allow absence of a value:

let target: Optional<Player> // may be absent
if target.hasValue {
target.takeDamage(10.0)
}

Short-circuits to null if absent:

let hp = target?.health

Use a fallback if absent:

let hp = target?.health ?? 0.0
let name = target?.name ?? "Nobody"

Functions that can fail return Result<T>. Errors are always string messages.

func divide(a: float, b: float) -> Result<float> {
if b == 0.0 {
return Error("Division by zero")
}
return Success(a / b)
}

Handle results with when:

when divide(10.0, 2.0) {
is Success(value) => print(value)
is Error(msg) => print("Failed: " .. msg)
}

Propagate errors up with ? — returns early on failure:

func calculate(a: float, b: float) -> Result<float> {
let quotient = divide(a, b)? // returns early on error
return Success(quotient * 2.0)
}

Use ?? instead of propagating:

let result = divide(10.0, 0.0) ?? 0.0