v0.4.0

Errors

A function that can fail says so in its signature: -> T throws E returns a T or throws an E. The error is an ordinary value of an ordinary type, and the caller deals with it where it calls — every call that can throw is marked with try, and the error is either handled there or passed on, visibly, to the caller's own caller.

function-result = [ "->" type ] [ "throws" type ]
throw-stmt      = "throw" expr ";"
SignatureMeaning
func F() -> T throws Ereturns a T, or throws an E
func F() throws Ereturns nothing, or throws an E
func F() -> T throws A | Breturns a T, or throws an A or a B — an error sum

Conditions that no caller could recover from — a broken invariant, a bug — are not errors in this sense. They stop the program with a panic.

Declaring the error

throws follows the return type, or the parameters when the function returns nothing. The error is the whole type after the keyword, so a sum needs no parentheses there, and a | before throws belongs to the success:

SignatureSuccessError
-> int32 | bool throws IoErrorint32 | boolIoError
-> int32 throws ParseError | IoErrorint32ParseError | IoError
-> int32? throws IoErrorint32?IoError
-> int32 throws (IoError?)int32an optional IoError

A suffix never reaches across throws: an optional error is grouped, and the ungrouped throws IoError? is error: an optional error type must be grouped with help: write 'throws (E?)'.

throws belongs to signatures — to functions and methods, to constructors (-> Self throws E), to function types such as func(int32) -> int32 throws Closed, and to interface requirements, which an implementation matches exactly, error included. It is not part of a type: there is no fallible type to store, pass or return (see No fallible type).

Throwing

throw value; sends an error. Outside a handler it leaves the function through its throws channel, and the value converts to the channel's type the way a return value converts to the return type — so a member of a sum channel is injected:

variant DivideError {
    ByZero,
    Inexact(int)
}

func ExactDivide(a: int, b: int) -> int throws DivideError {
    if b == 0 {
        throw .ByZero;
    }
    if a % b != 0 {
        throw .Inexact(a % b);
    }
    return a / b;
}

func Save(ok: bool) throws IoError {
    if !ok {
        throw IoError { code: 28 };
    }
    PrintLine("saved");
}
WriteProduces
return value;the success, value
throw error;the error, and leaves the function
return;completion, in a function that returns nothing
falling off the endcompletion, in a function that returns nothing

A case written without its type, as in throw .ByZero;, takes the error type of where it goes: the throws clause, or the errors the try block around it has seen so far. When that is a sum, write the owner, as in throw ParseError::Invalid(at). A unit error is thrown as throw ();.

throw leaves like return: the error is evaluated and captured first, then deferred statements run and live locals are destroyed. It needs no try. Inside a try block it goes to that block's catch arms instead; anywhere else it needs a function that throws:

error: 'throw' needs a function that throws, but 'Parse' returns 'int'
  help: declare 'throws E' on the function, or throw inside 'try { ... } catch { ... }'

throw is a statement, and also a whole arm body — of a match or catch arm — and the whole right side of ??, as in lookup ?? throw NotFound {}. In those places it produces no value and never decides the type of the result.

A function that declares throws E and no return type completes with the unit () when it returns or falls off its end. A function with no return type and no throws is a void function, and a type that merely contains the unit, such as ()?, still needs a value.

Error types

An error is an ordinary value of an ordinary type. There is no base error type, no error interface, and no implicit conversion between error types. Common choices:

Error typeUse it when
a structone kind of failure, with details: IoError { code: 28 }
a variantseveral named kinds, each with its own payload: DivideError::Inexact(1)
an enumseveral kinds with no payload
a sum, A | Bthe failures of several steps, each kept with its own type
()only the fact of failure matters: throws (), throw ();

An error sum widens implicitly: an error passes on as itself, as a member of the sum, or as a smaller sum of its members. A public function usually names a variant instead, so that its error does not change every time an internal step gains a failure, and so that it can carry the original cause; a type alias of a sum hides none of its members.

Calling a function that throws

A call to a function that throws is a throw site, and every throw site is marked with try in one of four forms:

FormWhere the error goesPage
try exprto the innermost handler around it, or out of the function through its throws channelPropagation
try expr catch { arms }to the arms, which produce a value of the operand's type or leaveHandling
try? exprdropped: the result is the value made present, T?, or noneHandling
try { ... } catch { arms }to the arms; every statement in the block is coveredHandling
func Show(a: int, b: int) {
    let quotient = try ExactDivide(a, b) catch {
        .ByZero => {
            PrintLine("division by zero");
            return;
        },
        .Inexact(rest) => {
            PrintLine("remainder {}", rest);
            return;
        }
    };
    PrintLine("= {}", quotient);
}

A throwing call evaluates to its success, so try ExactDivide(12, 2) / 2 divides the quotient. An unmarked call is an error, so an error can never be stored, ignored or matched by accident:

error: call to 'ExactDivide' can throw 'DivideError' but is not marked with 'try'
  help: write 'try' before the expression

The same holds for a throwing method, constructor, operator or interface requirement, and for a call through a function value whose type declares throws.

Errors are values

Rux errors do not unwind. A function that throws returns its success or its error as one tagged value, so each throw site is the call, a test of the tag and a branch: to the code that continues on success, and on failure to the handler around the call within the same function, or out of the function as an ordinary return.

  • Nothing walks the stack, and a throw costs what a return costs: a tag test and a branch at each frame it passes.
  • The error travels in the caller's result slot, never on the heap.
  • A function that does not throw returns its plain type, and a call to it has no tag test. Code that cannot fail pays nothing for errors elsewhere.
  • Only a marked throw site can leave a function early, so every exit is visible in the source.

The result is an 8-byte tag followed by the success or the error; a function that throws E and returns nothing returns the tag and an E. The tag values are not a stable ABI. See Layout.

A throwing Main

Main may declare throws E, with an int result or none, so the top level of a program can pass errors on with try:

Main declaresExit status on successWhen an error reaches it
throws E01
-> int throws Ethe returned int1

An error that reaches Main runs every defer and destructor on the way out and ends the program with status 1 without printing anything. Report what the user needs to know before throwing.

Keeping an outcome

An error is handled at the call or passed on, so nearly every call leaves nothing to store. An outcome that has to outlive the call — kept in a field or a container, sent elsewhere, or decided later — is Core's Result<T, E>, an ordinary variant Result<T, E> { Success(T), Failure(E) } with no compiler privileges:

import Core::Result;

func Store(a: int, b: int) -> Result<int, DivideError> {
    return try .Success(ExactDivide(a, b)) catch { e => .Failure(e) };
}

func Report(stored: Result<int, DivideError>) {
    if stored is .Success(_) {
        PrintLine("kept a quotient");
    }
    match stored {
        .Success(value) => PrintLine("= {}", value),
        .Failure(_) => PrintLine("kept an error")
    }
}

The type the context expects of the whole try ... catch is the operand's and every arm's, so .Success and .Failure need no variant written. is asks which case a stored result holds and borrows it rather than consuming it; match takes it apart. ?, ?? and try do not apply to a Result: it is a value, not a throw site.

No fallible type

Failure is not a type. The older fallible spellings are rejected, each with a help line naming its replacement:

Removed spellingErrorWrite instead
-> T ! E, -> ! E, T ! E as any type'T ! E' is not a type-> T throws E, throws E, or a stored Result<T, E>
fail error;'fail' is not supportedthrow error;
value? on a throwing call'?' does not propagate errorstry value
value? else (e => mapped)'? else' is not supportedtry value catch { e => throw mapped }
value catch { arms }'catch' must follow 'try'try value catch { arms }
error: 'T ! E' is not a type
  help: declare the error after the return type, as in '-> T throws E', or store an outcome in 'Result<T, E>'

.Success(value) and .Failure(error) are ordinary case spellings with no native meaning: they build the cases of an expected variant that declares them, such as Result, and are an error anywhere else. A function returns its success with return value; and its error with throw error;. fail and finally stay reserved words.

See also