Error Handling
Kira uses the Result[T, E] and Option[T] types for error handling instead of exceptions.
The Result Type
type Result[T, E] =
| Ok(T)
| Err(E)Working with Results
fn divide(a: i32, b: i32) -> Result[i32, string] {
if b == 0 {
return Err("Division by zero")
}
return Ok(a / b)
}
effect fn main() -> void {
let result: Result[i32, string] = divide(10, 2)
match result {
Ok(n) => { std.io.println("Result: " + to_string(n)) }
Err(e) => { std.io.println("Error: " + e) }
}
}The Try Operator
In effect functions, use ? to propagate errors:
effect fn process() -> Result[i32, string] {
let a: i32 = divide(10, 2)? // Propagates Err if division fails
let b: i32 = divide(a, 2)? // Propagates Err if this fails
return Ok(b)
}The ? operator unwraps Ok values and propagates Err values automatically.
The Option Type
For values that may not exist:
type Option[T] =
| Some(T)
| Nonefn find_user(id: i64) -> Option[User] {
// Return Some(user) if found, None otherwise
}
effect fn main() -> void {
let user: Option[User] = find_user(42)
match user {
Some(u) => { std.io.println("Found: " + u.name) }
None => { std.io.println("User not found") }
}
}Null Coalesce Operator
Use ?? to provide a default value for Option types:
let value: i32 = maybe_value ?? 0 // Use 0 if maybe_value is None
let name: string = maybe_name ?? "Anonymous"