Guides · 07

Optionals and errors

Vyi writes absence and failure into the type. A function that might have no answer returns ?T, an optional: a T or nothing. A function that can fail returns E!T, a result: a T, or an error of type E. This guide shows how to make both, how to use them, and how a failure reaches main.

Three rules run through all of it:

  • An optional or a result is an ordinary enum. Some, None, Ok, and Err are its variants, not keywords.
  • You construct every Some and Ok yourself. A plain value never becomes one on its own.
  • A failure leaves a function only through its return value. The errors a function can return are part of its signature.

Optionals

Vyi has no null. A value that might be absent has the type ?T, and the absent case is the variant None. The present case is Some, which holds the value:

Vyi
import { println } from "@fmt"

fn findAge(name: [*con]u8) ?i32 {
    if name == "ada" { return Some(36) }
    return None
}

fn main() !u8 {
    match findAge("ada") {
        Some(age): println(age),   // prints 36
        None:      println("not found"),
    }
    return Ok(0)
}

?T is a shorter way to write Optional(T), an enum in @core with two variants, None and Some(T). The two spellings name the same type.

You write the Some yourself. Returning a plain i32 from a function that returns ?i32 is an error:

Vyi · does not compile
fn half(n: i32) ?i32 {
    return n / 2   // error: this value has type i32, but the function returns Optional(i32)
}

Write return Some(n / 2) instead.

Some and None need an expected type

Some and None are variant names, and a bare variant name needs the code around it to say which enum it belongs to. A binding with no type gives no such hint, so this common first attempt fails:

Vyi · does not compile
fn main() !u8 {
    con port = Some(8080)   // error: cannot infer enum
    return Ok(0)
}

The full message is "cannot infer enum constructor type from the surrounding code". For a bare None it reads "enum variant" in place of "enum constructor". Give the binding a type, and both work:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con port: ?i32 = Some(8080)
    con proxy: ?i32 = None
    if Some(p) = port {
        println(p)            // prints 8080
    }
    if proxy == None {
        println("no proxy")   // prints no proxy
    }
    return Ok(0)
}

The expected type comes from wherever a value goes: a binding's declared type, a function's return type, a parameter's type when you pass an argument, the binding on the left of an assignment, the other side of ==, and the subject of a pattern. These are the same rules every enum follows (guide 03).

Using an optional

Because an optional is an enum, you take it apart with the tools from guide 06. Three forms cover most code:

Vyi
import { println } from "@fmt"

fn findAge(name: [*con]u8) ?i32 {
    if name == "ada" { return Some(36) }
    return None
}

fn main() !u8 {
    match findAge("bob") {
        Some(age): println(age),
        None:      println("not found"),   // prints not found
    }

    if Some(age) = findAge("ada") {
        println(age)                       // prints 36
    }

    con age = findAge("bob") catch 0
    println(age)                           // prints 0
    return Ok(0)
}
  • match handles both variants, one arm each.
  • An if binding runs its block only when the value is a Some.
  • catch takes the value out of a Some, or gives the fallback after it for a None. findAge("bob") catch 0 is 0. The catch section has its other forms.

A fourth form, try, passes the None on to your own caller. It works the same way for results, so it has its own section below.

An optional narrows like any enum. After if o == None { return ... }, the compiler knows o holds a Some, so a destructuring declaration can take the value out:

Vyi
import { println } from "@fmt"

fn orZero(o: ?i32) i32 {
    if o == None { return 0 }
    con Some(v) = o
    return v
}

fn main() !u8 {
    println(orZero(Some(7)))   // prints 7
    println(orZero(None))      // prints 0
    return Ok(0)
}

Without the test, con Some(v) = o is rejected, because o may still be None (guide 06).

?T is a type like any other. A struct field, a parameter, or an element can be optional:

Vyi
import { println } from "@fmt"

struct Config {
    host: [*con]u8,
    port: ?i32,
}

fn effectivePort(c: Config) i32 {
    return c.port catch 80
}

fn main() !u8 {
    con c = Config{ host: "localhost", port: None }
    println(effectivePort(c))   // prints 80
    return Ok(0)
}

A pointer is never null either. A pointer that might be missing is an optional pointer, such as ?*mut i32 (guide 09).

Results

A function that can fail returns E!T: a T on success, an E on failure. E!T is a shorter way to write Result(E, T), an enum in @core with two variants: Ok(T) carries the success value and Err(E) carries the error. The error can be any type. An enum of the things that can go wrong is the usual choice:

Vyi
import { println } from "@fmt"

enum AgeError { Negative, TooOld }

fn checkAge(age: i32) AgeError!i32 {
    if age < 0 { return Err(Negative) }
    if age > 150 { return Err(TooOld) }
    return Ok(age)
}

fn main() !u8 {
    match checkAge(36) {
        Ok(age): println(age),       // prints 36
        Err(_):  println("error"),
    }
    match checkAge(-1) {
        Ok(age):       println(age),
        Err(Negative): println("negative"),   // prints negative
        Err(TooOld):   println("too old"),
    }
    return Ok(0)
}

As with optionals, you write Ok(age) yourself, never a bare age. The variant names find their enum from the expected type, and that reaches inside the construction too. In return Err(Negative), the return type says Err belongs to AgeError!i32, so Err expects an AgeError, so Negative means AgeError.Negative.

The error travels as an ordinary value inside Err. Returning one is an ordinary return: nothing is allocated and no other code runs.

A function that can fail but has no value to give on success returns E!(). Its success value is (), the empty tuple from guide 02, so it ends with Ok(()):

Vyi
import { println } from "@fmt"

enum SaveError { DiskFull }

fn save(spaceLeft: i32) SaveError!() {
    if spaceLeft == 0 { return Err(DiskFull) }
    return Ok(())
}

fn main() !u8 {
    if Err(_) = save(0) {
        println("not saved")   // prints not saved
    }
    return Ok(0)
}

try: pass the failure on

Checking every result with match gets long when all you want is to stop and report the failure to your caller. try expr does that. On success it gives the value inside the Ok. On failure it returns the Err from the enclosing function, right there:

Vyi
import { println } from "@fmt"

enum MathError { DivByZero }

fn div(a: i32, b: i32) MathError!i32 {
    if b == 0 { return Err(DivByZero) }
    return Ok(a / b)
}

fn average(total: i32, count: i32) MathError!i32 {
    con avg = try div(total, count)
    return Ok(avg)
}

fn main() !u8 {
    println(average(30, 3) catch -1)   // prints 10
    println(average(30, 0) catch -1)   // prints -1
    return Ok(0)
}

When div fails, average returns that same Err(DivByZero) and runs nothing after the try.

try works anywhere an expression goes, as in return Ok(try div(a, b)). As a statement on its own, try save(n) runs the call, passes on a failure, and discards the success value.

On an optional, try gives the value inside the Some, or returns None from the enclosing function:

Vyi
import { println } from "@fmt"

fn half(n: i32) ?i32 {
    if n % 2 != 0 { return None }
    return Some(n / 2)
}

fn quarter(n: i32) ?i32 {
    con h = try half(n)
    return half(h)
}

fn main() !u8 {
    println(quarter(12) catch -1)   // prints 3
    println(quarter(6) catch -1)    // prints -1
    return Ok(0)
}

try stays in one channel

What try returns must fit the enclosing function's return type. A None passes through a function that returns an optional. An Err passes through a function that returns a result. Neither crosses to the other kind, because a None carries no error to put in an Err, and an Err would lose its error as a None:

Vyi · does not compile
enum LookupError { Missing }

fn find(id: i32) ?i32 {
    if id == 0 { return None }
    return Some(id)
}

fn get(id: i32) LookupError!i32 {
    con v = try find(id)   // error: a `None` carries no
    return Ok(v)
}

try is also rejected on a value that can't fail, such as a plain i32, and inside a function whose return type is neither an optional nor a result. To turn one kind of failure into the other, decide what it should become, and say so with catch.

catch: handle a failure

expr catch fallback gives the success value of expr, or, on failure, the fallback. What follows catch takes one of four forms:

  • An expression. expr catch 0 gives 0. Any expression works, such as expr catch limit + 1, so a lone value needs no braces.
  • A block. expr catch { ... } runs the statements in the block and gives its last expression. Use it when the fallback takes more than one statement. The block can also leave the function with return.
  • A function. expr catch onError calls onError with the error and gives what it returns.
  • An arrow function. expr catch (e: E) T => body works the same way, written in place.
Vyi
import { println } from "@fmt"

enum MathError { DivByZero, Overflow }

fn div(a: i32, b: i32) MathError!i32 {
    if b == 0 { return Err(DivByZero) }
    return Ok(a / b)
}

fn onError(e: MathError) i32 {
    return match e {
        DivByZero: -1,
        Overflow:  -2,
    }
}

fn main() !u8 {
    con a = div(40, 4) catch 0
    println(a)   // prints 10

    con b = div(9, 0) catch {
        println("cannot divide")   // prints cannot divide
        0
    }
    println(b)   // prints 0

    con c = div(9, 0) catch onError
    println(c)   // prints -1

    con d = div(9, 0) catch (e: MathError) i32 => 7
    println(d)   // prints 7
    return Ok(0)
}

On an optional the same forms apply. A None carries nothing, so a function after catch takes no parameters.

When the success type is (), there is no value to fall back to, and a block after catch runs only for its effect:

Vyi
import { println } from "@fmt"

enum SaveError { DiskFull }

fn save(spaceLeft: i32) SaveError!() {
    if spaceLeft == 0 { return Err(DiskFull) }
    return Ok(())
}

fn main() !u8 {
    save(0) catch {
        println("not saved")   // prints not saved
    }
    return Ok(0)
}

A catch block that returns is how a failure changes kind. Here a missing value becomes a real error:

Vyi
import { println } from "@fmt"

enum LookupError { Missing }

fn find(id: i32) ?i32 {
    if id == 0 { return None }
    return Some(id)
}

fn get(id: i32) LookupError!i32 {
    con v = find(id) catch {
        return Err(Missing)
    }
    return Ok(v)
}

fn main() !u8 {
    match get(0) {
        Ok(v):        println(v),
        Err(Missing): println("missing"),   // prints missing
    }
    return Ok(0)
}

The other direction works the same way: parse(s) catch { return None } in a function that returns an optional drops the error.

Inferred error types: !T

Writing out every error type gets tedious, so the error side can be left to the compiler. !T is a result whose error type the compiler works out from the function's body. It is the union of every error the body can produce:

Vyi
import { println } from "@fmt"

enum NetError { Down }
enum BodyError { TooLarge }

fn load(size: i32) !i32 {
    if size == 0 { return Err(NetError.Down) }
    if size > 99 { return Err(BodyError.TooLarge) }
    return Ok(size)
}

fn main() !u8 {
    match load(500) {
        Ok(n):             println(n),
        Err(_: NetError):  println("down"),
        Err(_: BodyError): println("too big"),   // prints too big
    }
    return Ok(0)
}

The error type of load is NetError | BodyError. With no expected enum to look in, the Err arguments name their enum: NetError.Down.

The compiler collects the error type from three kinds of site in the body:

  • Each return Err(e) adds the type of e.
  • Each try adds the error type of the call it unwraps. Errors pass up a chain of calls without being written anywhere.
  • A body with neither always succeeds. Its error type is empty, and a catch on its result never runs its fallback.

The error type comes from the function's own body, never from its callers.

Vyi
import { println } from "@fmt"

enum IoError { Closed }

fn read(fd: i32) !i32 {
    if fd == 0 { return Err(IoError.Closed) }
    return Ok(fd)
}

fn readPlusOne(fd: i32) !i32 {
    con v = try read(fd)
    return Ok(v + 1)
}

fn main() !u8 {
    println(readPlusOne(5) catch 0)   // prints 6
    println(readPlusOne(0) catch 0)   // prints 0
    return Ok(0)
}

readPlusOne never mentions IoError, and its error type is still exactly IoError, taken from the try.

Bare ! is the inferred form of E!(): it can fail, and it gives nothing on success. main returns !u8, an inferred error type with a u8 success value; the last section explains why.

Narrower errors flow into wider ones

An error type is a union, so a narrower one fits where a wider one is expected. A function declared with the error type NetError | ParseError can try a call whose error type is only NetError:

Vyi
import { println } from "@fmt"

enum NetError { Down }
enum ParseError { Bad }

fn fetch(n: i32) NetError!i32 {
    if n == 0 { return Err(NetError.Down) }
    return Ok(n)
}

fn loadDoc(n: i32) (NetError | ParseError)!i32 {
    con raw = try fetch(n)
    if raw > 99 { return Err(ParseError.Bad) }
    return Ok(raw)
}

fn main() !u8 {
    println(loadDoc(5) catch 0)   // prints 5
    println(loadDoc(0) catch 0)   // prints 0
    return Ok(0)
}

The other way round is rejected: try on a call with error type NetError | ParseError, inside a function declared to fail only with NetError, is an error.

Write the error type where there is no body

A function type, such as the type of a parameter that takes a function, has no body to work from, so !T there is an error. Write the error type out:

Vyi · does not compile
fn run(f: fn() !i32) i32 {   // error: cannot infer error type
    return f() catch 0
}

Overloads don't differ by failure

Overloaded functions differ in their parameter types, never only in their return type. A parse(s) i32 next to a parse(s) ParseError!i32 is a duplicate declaration. Give the two different names, or let the caller pass the result type as a known T: type parameter (guide 11).

error declarations

Many failures are a fixed set of named conditions, each with a message for a person to read. An error declaration states both in one place. It has two forms:

Vyi
import { println } from "@fmt"

error DiskFull "disk is full"

error ParseError {
    Unexpected "unexpected token";
    Eof "end of input";
}

fn parseBool(s: [*con]u8) ParseError!bool {
    if s.len == 0 { return Err(Eof) }
    if s == "true" { return Ok(true) }
    if s == "false" { return Ok(false) }
    return Err(Unexpected)
}

fn main() !u8 {
    if Ok(flag) = parseBool("true") {
        println(flag)      // prints true
    }
    if Err(Eof) = parseBool("") {
        println("empty")   // prints empty
    }
    return Ok(0)
}
  • The single form, error DiskFull "disk is full", declares one error. Its value is written DiskFull.
  • The block form declares several members, separated by ;. Each member is written by its path, ParseError.Eof, or by its bare name where the expected type is ParseError.

A member carries its message and nothing else. It can't hold data such as a line number. For an error that needs data, use an enum with a message method, described below.

When an error member reaches the end of main, the program prints its message. There is no method to write. The standard library declares its failures this way: OutOfMemory in @mem, and ReadError and WriteError in @io.

The open error type

error on its own is also a type: the open error type. A member of any error declaration converts to it, so a function that returns error!T can fail with errors from many declarations, including ones it has never seen:

Vyi
import { println } from "@fmt"

error DiskFull "disk is full"

error ParseError {
    Unexpected "unexpected token";
    Eof "end of input";
}

fn save(text: [*con]u8) error!() {
    if text.len == 0 { return Err(ParseError.Eof) }
    if text.len > 5 { return Err(DiskFull) }
    return Ok(())
}

fn describe(e: error) [*con]u8 {
    return match e {
        DiskFull:       "no space",
        ParseError.Eof: "nothing to save",
        default:        "something else",
    }
}

fn main() !u8 {
    if Err(e) = save("") {
        println(describe(e))   // prints nothing to save
    }
    if Err(e) = save("a long text") {
        println(describe(e))   // prints no space
    }
    return Ok(0)
}

save fails with a member of ParseError for empty text and with DiskFull for text longer than five bytes. Both leave as an error.

A match over an error names a single-form error by its name and a block member by its path. No list of arms can cover an open set, so the match needs a default arm. Without one, the compiler says "a match over error needs a default arm: an open error set cannot be covered by arms".

Error messages: @errmsg

Any type can be an error. To give an enum or a struct error a message, declare the method @errmsg on it, returning the text. When the error reaches the end of main, the program prints what @errmsg returns, and you can call it yourself:

Vyi
import { println } from "@fmt"

enum MathError { DivByZero }

fn (e: MathError) @errmsg() [*con]u8 {
    return "division by zero"
}

fn div(a: i32, b: i32) MathError!i32 {
    if b == 0 { return Err(DivByZero) }
    return Ok(a / b)
}

fn main() !u8 {
    if Err(e) = div(1, 0) {
        println(e.@errmsg())   // prints division by zero
    }
    return Ok(0)
}

The @ marks a method that the language itself calls. Guide 13 covers these methods.

An inferred error type can be a union of several error types. If each of them declares @errmsg, calling e.@errmsg() on the union calls the method of whichever error it holds.

Errors with a call stack: @errors

The @errors package exports Error, a struct error that holds a message and the call stack at the moment you build it. Error.new(message) makes one. The stack is recorded when the error is built, not when it is passed on: by the time an Err has gone up through several trys, the calls that explain it have already returned.

Vyi
import { println } from "@fmt"
import { Error } from "@errors"

fn open(name: [*con]u8) Error!i32 {
    return Err(Error.new("file not found"))
}

fn load() Error!i32 {
    con fd = try open("config")
    return Ok(fd)
}

fn main() !u8 {
    if Err(e) = load() {
        con stack = e.@errstack()
        println(e.@errmsg())   // prints file not found
        println(stack.len)              // prints 2
        println(stack.frames[0].line)   // prints 14
        println(stack.frames[1].line)   // prints 9
    }
    return Ok(0)
}

@errstack gives the recorded stack. Each frame is a call that was in progress, oldest first, with its file, line, and col: main calling load on line 14, then load calling open on line 9. Recording a stack allocates nothing. It holds up to 32 calls, and when there were more it keeps the innermost ones.

main returns !u8

Every program's main is fn main() !u8, and any other signature is an error. The result of main decides how the program ends:

  • Ok(code) exits with code as the exit status. return Ok(0) reports success.
  • Err(e) prints error: and the error's message on standard error, and exits with status 1. The message is an error member's own text, or what @errmsg returns. An error type with neither prints error: alone.

So a failure that nothing handles reaches the user as a readable message:

Vyi
error NoConfig "config file missing"

fn readConfig() NoConfig!u8 {
    return Err(NoConfig)
}

fn main() !u8 {
    con level = try readConfig()
    return Ok(level)
}

This program prints error: config file missing on standard error and exits with status 1. The error type of main is inferred like any !T, so try in main passes on any error.

Errors and panics

A function's errors are part of its return type. Reading a signature tells you whether a call can fail: a function that returns i32 gives back an i32, and the caller has no failure to handle.

Some problems are not errors, because no caller could do anything useful about them: an index out of bounds, a division by zero, or a Vec that can't grow because its allocator is out of memory. These panic. A panic is not a return value and is not in any signature. It stops the program with a message and a stack trace, unless a recover catches it. Guide 08 covers panics.

The line between the two is a choice each function makes. An allocator's new returns OutOfMemory as an error, so the caller decides what to do. Vec.push returns nothing, so when it can't get memory it panics. Guide 10 covers collections.

See also: reference/error-model, reference/stdlib/core.