v0.4.0
Errors · Lesson 9.2

Fail

Source
Leave a function through its throws channel with throw, carrying an error that says what went wrong.
You'll need: Fallible, Struct

A throwing function has two ways out. return value; is the success, as the previous lesson showed. throw is the other one: it leaves the function at once through its throws channel, carrying an error value for the caller.

This lesson is a cash machine. A withdrawal either answers with the new balance or refuses — and when it refuses, it says exactly how much money was missing.

The error is plain data

An error can be any type you like. Here it is a struct, so it can report exactly what went wrong — how much the account held and how much was asked for:

struct ShortOfFunds {
    balance: int;
    requested: int;
}

There is nothing special about the type itself. It becomes an error only because a signature names it after throws:

func Withdraw(balance: int, amount: int) -> int throws ShortOfFunds {

throw leaves at once

throw builds the error and hands it over in one statement. Nothing after a throw runs, just as nothing after a return does:

if amount > balance {
    throw ShortOfFunds { balance: balance, requested: amount };
}
// Only reached when the money is there.
return balance - amount;
StatementLeaves throughThe caller gets
return balance - amount;the successthe new balance, an int
throw ShortOfFunds { ... };the error channela ShortOfFunds

A throw costs what a return costs. Rux errors do not unwind the stack: the error travels back to the caller the way a returned value does.

Reading the details

The caller marks the call with try and gives a catch arm for the error. Written after a single call, try ... catch { ... } is an expression: on success it is the value, and on failure the arm runs. The arm either produces a value of the success type or leaves — here it prints and returns:

let left = try Withdraw(balance, amount) catch {
    error => {
        PrintLine("take {} from {}: refused, {} short", amount, balance, error.requested - error.balance);
        return;
    }
};

The arm error => ... binds the whole error, and because it is a struct, the arm reads its fields like any other. Taking exactly the whole balance is fine — amount > balance is false for 100 and 100, so Report(100, 100) leaves 0. An empty account refuses even 5.

Where throw is allowed

throw has two rules, and the compiler enforces both. Its value must have the error type named after throws — a ShortOfFunds here, not a number. And it belongs only in a function that throws, or inside a try block that catches it: Main returns a plain int, so a throw there has nowhere to go.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// A function that can fail has two ways out. `return value;` is the success, as the previous
// lesson showed. `throw` is the other one: it leaves the function at once through its `throws`
// channel, carrying an error value for the caller.
//
// The error can be any type you like. Here it is a struct, so it can report exactly what went
// wrong — how much money the account held and how much was asked for.
// `throw ShortOfFunds { ... };` builds that struct and hands it over in one statement. Nothing
// after a `throw` runs, just as nothing after a `return` does. A throw costs what a return costs:
// nothing unwinds the stack.
import Io::PrintLine;

// The error: plain data describing the problem, nothing special about the type itself.
struct ShortOfFunds {
    balance: int;
    requested: int;
}

// Answers with the new balance, or throws the details of why it could not.
func Withdraw(balance: int, amount: int) -> int throws ShortOfFunds {
    if amount > balance {
        throw ShortOfFunds { balance: balance, requested: amount };
    }
    // Only reached when the money is there.
    return balance - amount;
}

// `try` marks the call that can throw, and the `catch` arm runs only when it does. The arm either
// produces a value of the success type or leaves; here it prints and returns.
func Report(balance: int, amount: int) {
    let left = try Withdraw(balance, amount) catch {
        error => {
            PrintLine("take {} from {}: refused, {} short", amount, balance, error.requested - error.balance);
            return;
        }
    };
    PrintLine("take {} from {}: {} left", amount, balance, left);
}

func Main() -> int {
    Report(100, 30);
    Report(100, 100);
    Report(100, 130);
    Report(0, 5);

    // `throw` must carry a value of the error type named after `throws`. `throw 30;` inside
    // `Withdraw` is rejected — "'throw' value must have type 'ShortOfFunds', but found 'int'".
    // And `throw` belongs only in a function that throws: here in `Main`, which returns a plain
    // `int`, it is an error too — "'throw' needs a function that throws, but 'Main' returns
    // 'int'".
    return 0;
}

Run it

cd Examples/Errors/Fail
rux run
take 30 from 100: 70 left
take 100 from 100: 0 left
take 130 from 100: refused, 30 short
take 5 from 0: refused, 5 short

Common mistakes

Try it yourself

  1. Add Report(100, 101); and predict the shortfall it prints.
  2. Write Deposit(balance: int, amount: int) -> int throws TooMuch that refuses when the new balance would pass 1000, with a TooMuch struct that says by how much.
  3. Make Withdraw refuse a negative amount too. Is ShortOfFunds the right error for that? Error variant shows the better shape.

Learn more