v0.4.0
Errors · Lesson 9.14

Nested fallible

Source
Keep two meanings apart by nesting: -> int? throws E for "the next value, the end, or an error", and -> Result<int, E1> throws E2 for an answer that can itself be a failure.
You'll need: Nested optional, Outcome

A return type and a throws clause combine, and each level keeps its own meaning. You saw nesting with optionals in Nested optional; this lesson does the same with errors. Two shapes come up all the time, and both are about keeping two different answers apart.

The next value, the end, or an error

-> int? throws SensorError is the shape of "read the next value". Three answers are possible: a value, no more values, or the read itself broke:

func Reading(sensor: int, index: int) -> int? throws SensorError {

Running out is not an error, and a broken sensor is not "no more" — so both levels are needed. The catch deals with the thrown error, and a match on what comes back tells a value from the end:

let next = try Reading(sensor, index) catch {
    e => {
        PrintLine(" (sensor {} broke)", e.sensor);
        break;
    }
};
match next {
    .Some(value) => Print(" {}", value),
    none => {
        PrintLine(" (end)");
        break;
    }
}

A catch arm may leave the loop with break, just as it may leave the function with return.

WhereMeans
.Some(value)the read worked and found a value
nonethe read worked and found nothing more
the catch armthe read itself broke

Walking a folder in the FileSystem package has exactly this shape, as you will see in Directory.

An answer that can itself be a failure

-> Result<int, RangeError> throws SensorError is the shape of "ask for a result that can itself be a failure". The thrown error means the question never got an answer. A returned value holds the answer, and that answer is Core's Result, an ordinary variant: the sensor replied, and what it replied may be "out of range".

if sensor == 3 {
    throw SensorError { sensor: sensor };
}
let answer: Result<int, RangeError> = if sensor == 2 {
    .Failure(RangeError { value: 999 })
} else {
    .Success(21)
};
return answer;

An outcome that has to be handed back as data, rather than handled at the call, is stored this way.

flowchart LR
    test["`SelfTest(sensor)`"] --> outer{"Did the sensor answer?"}
    outer -- "it threw" --> none["no answer<br/>(a `SensorError`)"]
    outer -- "it returned" --> inner{"What did it answer?"}
    inner -- "`.Success(value)`" --> ok["a reading"]
    inner -- "`.Failure(e)`" --> range["out of range<br/>(a `RangeError`)"]

Levels never merge

The inner failure is ordinary data inside the returned value, so try and catch on the call never touch it. catch handles the thrown error; a match on what comes back reaches every other case:

try {
    match SelfTest(sensor) {
        .Success(value) => PrintLine("sensor {} test: reads {}", sensor, value),
        .Failure(e) => PrintLine("sensor {} test: {} is out of range", sensor, e.value)
    }
} catch {
    e => PrintLine("sensor {} test: no answer", e.sensor)
}

Sensor 2 did answer, so the catch has nothing to do, and the match prints 999 is out of range. Only sensor 3, which threw, reaches the catch arm.

The program

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

Src/Main.rux
// A return type and a `throws` clause combine, and each level keeps its own
// meaning. Two shapes come up all the time.
//
// `-> int? throws SensorError` — "read the next value". Three answers are
// possible: a value, no more values (`none`), or the read itself broke (an
// error). Running out is not an error and a broken sensor is not "no more",
// so both levels are needed. Walking a folder in the `FileSystem` package has
// exactly this shape.
//
// `-> Result<int, RangeError> throws SensorError` — "ask for a result that
// can itself be a failure". The thrown error means the question never got an
// answer. A returned value holds the answer, and that answer is Core's
// `Result`, an ordinary variant: the sensor replied, and what it replied may
// be "out of range". An outcome that has to be handed back as data, rather
// than handled at the call, is stored this way.
//
// Levels never merge. The inner failure is ordinary data inside the returned
// value, so `try` and `catch` on the call never touch it. `catch` handles the
// thrown error; a `match` on what comes back reaches every other case.
import Core::Result;
import Io::{ Print, PrintLine };

struct SensorError {
    sensor: int;
}

struct RangeError {
    value: int;
}

// Sensor 1 logged three readings. Sensor 2 broke while reading its third.
func Reading(sensor: int, index: int) -> int? throws SensorError {
    if sensor == 2 && index == 2 {
        throw SensorError { sensor: sensor };
    }
    if index >= 3 {
        return none;
    }
    return 20 + index;
}

// Sensor 1 answers 21, sensor 2 answers with a reading it rejects, and
// sensor 3 does not answer at all.
func SelfTest(sensor: int) -> Result<int, RangeError> throws SensorError {
    if sensor == 3 {
        throw SensorError { sensor: sensor };
    }
    let answer: Result<int, RangeError> = if sensor == 2 {
        .Failure(RangeError { value: 999 })
    } else {
        .Success(21)
    };
    return answer;
}

func Main() -> int {
    for sensor in 1..=2 {
        Print("sensor {} log:", sensor);
        for index in 0..10 {
            // A `catch` arm may leave the loop with `break`.
            let next = try Reading(sensor, index) catch {
                e => {
                    PrintLine(" (sensor {} broke)", e.sensor);
                    break;
                }
            };
            match next {
                .Some(value) => Print(" {}", value),
                none => {
                    PrintLine(" (end)");
                    break;
                }
            }
        }
    }

    for sensor in 1..=3 {
        try {
            match SelfTest(sensor) {
                .Success(value) => PrintLine("sensor {} test: reads {}", sensor, value),
                .Failure(e) => PrintLine("sensor {} test: {} is out of range", sensor, e.value)
            }
        } catch {
            e => PrintLine("sensor {} test: no answer", e.sensor)
        }
    }
    return 0;
}

Besides Io, its Rux.toml lists Core under [Dependencies].

Run it

cd Examples/Errors/NestedFallible
rux run
sensor 1 log: 20 21 22 (end)
sensor 2 log: 20 21 (sensor 2 broke)
sensor 1 test: reads 21
sensor 2 test: 999 is out of range
sensor 3 test: no answer

Common mistakes

Try it yourself

  1. Extend the first loop to sensor 3 with 1..=3. Predict its log line before you run.
  2. Make sensor 1's self-test answer 150 and treat anything over 100 as out of range.
  3. Write func FirstReading(sensor: int) -> int? throws SensorError that returns the reading at index 0 with plain try. What type does try Reading(sensor, 0) have?

Learn more

  • Nested optional — the same idea with T??
  • Outcome — Core's Result as patterns and constructors
  • Iterator — T? as "the next item, or the end"
  • Directory — a real -> T? throws E from the FileSystem package