# 7. Errors and nil Rex has no exceptions. A function that can fail says so in its result, and you handle it. ## error `error` is a type that is either `nil` (all fine) or holds a message. ```rex func parse_age(s: string): (int, error) { var n, err = s.to_int() if err != nil { return 0, error("'{s}' is not a number") } if n < 0 { return 0, error("age can't be negative") } return n, nil } func main() { var a, err = parse_age("42") print(a, err) var b, err2 = parse_age("abc") print(b, err2) } ``` ```text 42 nil 0 'abc' is not a number ``` - `error("text {value}")` makes an error. It can use `{ }` like any string. - `var value, err = f()` takes both results. Use `_` to ignore one. - You can't silently ignore an error: calling a function that returns an error as a bare statement is a compile error. ## `?`: pass the problem up Writing `?` after a call means "if this failed, return the error from *my* function too". Otherwise you get the value. ```rex func half(n: int): (int, error) { if n % 2 != 0 { return 0, error("{n} is odd") } return n / 2, nil } func quarter(n: int): (int, error) { var h = half(n)? var q = half(h)? return q, nil } func main() { var a, err = quarter(8) print(a, err) var b, err2 = quarter(6) print(b, err2) } ``` ```text 2 nil 0 3 is odd ``` `?` works in any function whose last result is `error`. `func main(): error` is allowed: if it returns an error, the program prints `error: message` and exits with code 1. ## Optional values: `T?` A `T?` is either a `T` or `nil`. It is how Rex says "this might be missing". ```rex func find(names: []string, wanted: string): int? { for i, n in names { if n == wanted { return i } } return nil } func main() { var names = ["ann", "bo", "cy"] var at = find(names, "bo") if at != nil { print("found at", at) } var missing = find(names, "zed") print(missing == nil) } ``` ```text found at 1 true ``` The compiler **requires** the check. It knows a value is set: - inside `if x != nil { ... }` - after `if x == nil { return }` (or `break` / `continue`) - on the right side of `x != nil && ...` Assigning to `x` makes the compiler forget that. (And even so, using a `nil` value stops the program with a message instead of misbehaving.) Maps give you optionals too: ```rex func main() { var ports = {"http": 80} var p = ports.get("https") if p == nil { print("no https") } } ``` ```text no https ``` Not available yet: `T?` as a struct field or list item, and `??`. Next: [Memory](08-memory.md)