Errors
Zyn separates two kinds of errors:
- Failures you expect, like text that isn't a number or a file that isn't there, are values: a function returns a
Result, and the caller decides what to do. - Bugs, like an index past the end of a list, stop the program with a clear message.
panicdoes that on purpose.
#Result
Result<T, E> is either Ok(value) with a value of type T, or Err(error) with an error of type E:
fn divide(a: Int, b: Int): Result<Int, String> {
if b == 0 { return Err("can't divide {a} by zero") }
return Ok(a / b)
}
println(divide(10, 2))
println(divide(1, 0))Ok(5) Err(can't divide 1 by zero)
Result is an ordinary enum, so match handles both cases:
fn divide(a: Int, b: Int): Result<Int, String> =
if b == 0 { Err("division by zero") } else { Ok(a / b) }
for b in [5, 0] {
match divide(10, b) {
Ok(value) -> println("got {value}")
Err(message) -> println("failed: {message}")
}
}got 2 failed: division by zero
The type checker won't let you use a Result as if it were its value: you have to look inside.
#Passing errors on with try
Most code can't fix an error itself, and passes it to its caller. try does that: for an Ok it gives the value; for an Err, it returns that Err from the function at once.
data Size(width: Int, height: Int)
fn parseSize(text: String): Result<Size, String> {
let parts = text.split("x")
if parts.size != 2 { return Err("expected WIDTHxHEIGHT, got '{text}'") }
let w = try parts[0].toInt()
let h = try parts[1].toInt()
return Ok(Size(w, h))
}
println(parseSize("1920x1080"))
println(parseSize("1920"))
println(parseSize("wide x 1080"))Ok(Size(width=1920, height=1080))
Err(expected WIDTHxHEIGHT, got '1920')
Err('wide ' is not a whole number)try works in a function whose return type is a Result with a fitting error type. It can't be used in lambdas or at the top level of a script.
#Working with results
Result has helper functions, so a match isn't always needed:
let good = "42".toInt()
let bad = "forty-two".toInt()
println(good.getOrElse(0))
println(bad.getOrElse(0))
println(bad.getOrNull())
println(bad.errorOrNull())
println(good.isOk())
println(good.map { it * 2 })
println(bad.mapErr { "Oops: {it}" })
println(good.andThen { n -> if n > 100 { Ok(n) } else { Err("too small") } })42 0 null 'forty-two' is not a whole number true Ok(84) Err(Oops: 'forty-two' is not a whole number) Err(too small)
unwrap() gives the value of an Ok, and stops the program for an Err. Use it when an Err would be a bug:
let port = "eighty".toInt().unwrap()Panic: unwrap() was called on Err('eighty' is not a whole number) --> <prelude>:48:24 | 48 | | ^
All of these are listed in the standard library.
#Your own error types
The error can be any type. An enum describes the ways something can fail, and match makes sure each is handled:
enum LoginError {
UnknownUser(name: String)
WrongPassword
Locked(minutes: Int)
}
fn login(name: String, password: String): Result<String, LoginError> = match {
name != "ada" -> Err(UnknownUser(name))
password != "secret" -> Err(WrongPassword)
_ -> Ok("token-123")
}
fn explain(e: LoginError): String = match e {
UnknownUser(n) -> "nobody is called {n}"
WrongPassword -> "wrong password"
Locked(m) -> "try again in {m} minutes"
}
for attempt in [["bob", "x"], ["ada", "x"], ["ada", "secret"]] {
match login(attempt[0], attempt[1]) {
Ok(token) -> println("logged in: {token}")
Err(e) -> println("can't log in: {explain(e)}")
}
}can't log in: nobody is called bob can't log in: wrong password logged in: token-123
#Panic
panic(message) stops the program with an error. It's for things that should never happen; a program that panics ends with exit code 70.
fn percent(part: Int, whole: Int): Int {
if whole == 0 { panic("percent of nothing") }
return part * 100 / whole
}
println(percent(1, 4))
println(percent(1, 0))25 Panic: percent of nothing --> main.zyn:2:26 | 2 | if whole == 0 { panic("percent of nothing") } | ^
Errors while running show the line they happened on, in every way of running a program: interpreted, as a jar and native. Other runtime errors work the same way: an index out of bounds, dividing an Int by zero, a too-big Int, a failed assert, endless recursion.
#Assertions
assert(condition) and assertEq(actual, expected) stop the program when something isn't as it should be. They're mostly used in tests, but work anywhere:
let items = [1, 2, 3]
assert(items.size == 3)
assertEq(items.sum(), 7)Assertion failed: expected 7, but got 6 --> main.zyn:3:9 | 3 | assertEq(items.sum(), 7) | ^