Docs/Language basics

Error handling

Declare, throw, and handle errors.

On this page

A function that can fail declares an error type, and every caller must decide what to do when it fails: use a fallback, run a handler, or pass the error on.

Declare and throw an error#

Error types are named union types:

Valk
union QuantityError {
    not_positive
    too_large
}

fn checked_quantity(value: int) int !QuantityError {
    if value <= 0 : throw .not_positive
    if value > 100 : throw .too_large
    return value
}

fn main() {
    println(checked_quantity(5) !? 1)   // 5
    println(checked_quantity(-2) !? 1)  // 1
}

!QuantityError after the result type says the function may throw a QuantityError; throw .variant leaves the function with that error.

Handle an error#

Form On failure
call() !? value Use a fallback value
call() ! { ... } Run a handler
call() ! return Run one statement
call() !> Pass the error to your caller
call() !! Panic with the error
call() _ Ignore the error (and the result)

Use !! only when failure means a bug, and _ only when the outcome really does not matter.

Fall back to a value#

Valk
fn main() {
    let port = "abc".to(int) !? 8080
    println(port)  // 8080
    let retries = "x".to(int) !? <{
        println("Invalid retries, using 3")
        return 3
    }
    println(retries)
}

A <{ ... } block runs several statements before giving the fallback. !? binds tighter than comparisons, so count() !? 0 == 3 means (count() !? 0) == 3.

Run a handler#

Valk
fn main() {
    let quantity = "many".to(int) ! {
        println("Enter a whole number, such as 3.")
        return
    }
    println("Quantity: %quantity")
}

When the call's value is used, the handler must leave the flow: return, throw, break, continue or panic.

Pass an error to the caller#

Valk
fn doubled_input(text: String) int !SyntaxError {
    let value = text.to(int) !>
    return value * 2
}

fn main() {
    let result = doubled_input("21") ! {
        println("Could not parse the input.")
        return
    }
    println(result) // 42
}

!> returns the error from the current function. The enclosing function's error type must match, or have an $auto variant that wraps it.

Check which error happened#

Inside a handler, E is the thrown union value. Match it with match E, or test a variant with E is .variant:

Valk
union LoadError {
    missing
    denied
}

fn load(name: String) String !LoadError {
    if name == "secret" : throw .denied
    throw .missing
}

fn main() {
    load("secret") ! {
        match E {
            .missing => println("not found")
            .denied => println("access denied")
        }
    }
    load("x") ! {
        if E is .missing : println("missing")
    }
}

is .variant works on both payloadless and payload variants (and on nullable unions). All standard library error unions also define to_string() String $auto, so "%{E}" and "failed: " + E format them directly.

Attach details to an error#

Each variant can carry its own payload values, and the union can define methods or getters:

Valk
union NameError {
    empty(String)
    too_long(String, uint)
}

fn check_name(name: String) !NameError {
    if name.is_empty() : throw .empty("A name is required.")
    if name.length > 10 : throw .too_long("Too long.", 10)
}

fn main() {
    check_name("") ! {
        match E {
            .empty(msg) => println(msg)
            .too_long(msg, limit) => println("%msg Max %limit")
        }
    }
    check_name("Bartholomew the Great") ! {
        match E {
            .empty(msg) => println(msg)
            .too_long(msg, limit) => println("%msg Max %limit")
        }
    }
}

Combine error types#

Mark a wrapping variant with $auto so !> and throw wrap lower-level errors automatically (including transitively across layers):

Valk
union ConfigError {
    missing
    syntax(SyntaxError) $auto

    fn to_string() String $auto {
        return match this : String {
            .missing => "missing"
            .syntax(e) => e.to_string()
        }
    }
}

fn read_port(text: String) int !ConfigError {
    if text.is_empty() : throw .missing
    return text.to(int) !>   // auto-wraps SyntaxError into .syntax(e)
}

fn main() {
    read_port("") ! println("error: %{E}")   // error: missing
    read_port("x") ! println("error: %{E}")  // error: syntax
}

Built-in error types#

Type Variants Used for
GenericError error A generic failure
LookupError missing, exists, range, empty Finding or storing something, such as Array.get
SyntaxError syntax Parsing text, such as "x".to(int)
FormatError syntax, io(IoError) Writing formatted values with format_*_into
SystemError failed, unsupported The OS could not answer
IterError end Ending an each over a custom type
InitError init Setup that failed

Reuse error construction#

A function marked $throw must always throw. Call it where a throw would go:

Valk
union ParseError {
    invalid(String, uint)
}

fn parse_error(message: String, line: uint) !ParseError $throw {
    throw .invalid(message, line)
}

fn parse_line(text: String, line: uint) int !ParseError {
    if text.is_empty() : parse_error("empty line", line)
    return text.to(int) ! parse_error("not a number", line)
}

fn main() {
    parse_line("", 3) ! {
        match E {
            .invalid(msg, line) => println("%msg on line %line") // empty line on line 3
        }
    }
}

Panic#

panic("message") stops the program with exit code 1 and prints the message with the file and line. Build with -d (or --stack-traces) to get a full stack trace, see Debugging.

Errors are for calls that can fail. A value that may be missing is nullable instead and uses ??.