v0.4.0
Errors · Lesson 9.7

Catch fallback

Source
Use try call catch { _ => fallback }, or (try? call) ?? fallback, to get the success or a default value.
You'll need: Catch, Coalesce

Often the reason for a failure does not matter, only that there is a value to carry on with. try call catch { _ => fallback } says exactly that: the success if there is one, otherwise the fallback. The single _ arm takes every error alike, so nothing needs listing.

One arm for every error

A settings form where every field is one typed digit, each with a sensible default:

let volume = try ReadDigit('7') catch { _ => 5 };
let brightness = try ReadDigit('x') catch { _ => 8 };
let contrast = (try? ReadDigit(' ')) ?? 5;

'7' reads fine, so volume is 7. 'x' is not a digit and ' ' is blank — two different errors, and both get the field's default. The fallback must have the success type, an int here.

The twin of ??

If you have done Coalesce, the shape is familiar. catch { _ => ... } is the throwing twin of option ?? fallback — and try? connects the two. It drops the error and leaves an optional, int?, which ?? then fills in:

You haveValue or defaultThe fallback runs
an optional T?option ?? fallbackonly when absent
a call that throwstry call catch { _ => fallback }only on an error
a call that throws(try? call) ?? fallbackonly on an error

Like ??, the fallback is worked out only when it is needed. A fallback that calls a function which prints something prints nothing at all when the read succeeds.

Why not just ?? on the call itself? Because a throwing call gives its success, a plain int, not an optional — the error is not a value ?? could look at. The call still has to be marked, and try? is the mark that says dropping the error is intended.

Parentheses around an operand

try covers the whole expression to its right, so a try ... catch that is one operand of a larger expression sits in parentheses. Adding up a code, where a digit that cannot be read counts as nothing:

let total = (try ReadDigit('4') catch { _ => 0 }) + (try ReadDigit('?') catch { _ => 0 })
    + (try ReadDigit('9') catch { _ => 0 });

Each catch belongs to the ReadDigit inside its own parentheses, so the sum is 4 + 0 + 9 = 13. The same goes for try?: (try? ReadDigit(' ')) ?? 5 needs its parentheses, because without them the ?? would be inside the try?.

The price

The convenience has a price: the error is thrown away unseen. 'x' and ' ' both became defaults, and nothing in the program can tell which went wrong or why. When the reason should change what happens next, give catch one arm per case instead, as Catch does.

The program

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

Src/Main.rux
// Often the reason for a failure does not matter, only that there is a value to carry on with.
// `try call catch { _ => fallback }` says exactly that: the success if there is one, otherwise
// the fallback. The single `_` arm takes every error alike, so nothing needs listing.
//
// It is the throwing twin of `option ?? fallback`, and `(try? call) ?? fallback` says the same
// thing: `try?` drops the error and leaves an optional, and `??` supplies the default. Either way
// the fallback is only worked out when it is needed, and it must have the success type — an
// `int` here.
//
// `try` covers the whole expression to its right, so a `try ... catch` that is one operand of a
// larger expression sits in parentheses.
import Io::PrintLine;

variant DigitError {
    Blank,
    NotADigit(char)
}

func ReadDigit(c: char) -> int throws DigitError {
    if c == ' ' {
        throw DigitError::Blank;
    }
    if c < '0' || c > '9' {
        throw DigitError::NotADigit(c);
    }
    return (c as int) - ('0' as int);
}

func Main() -> int {
    // A settings form where every field is one typed digit, each with a sensible default.
    let volume = try ReadDigit('7') catch { _ => 5 };
    let brightness = try ReadDigit('x') catch { _ => 8 };
    let contrast = (try? ReadDigit(' ')) ?? 5;
    PrintLine("volume {}, brightness {}, contrast {}", volume, brightness, contrast);

    // Adding up a code, where a digit that cannot be read counts as nothing.
    let total = (try ReadDigit('4') catch { _ => 0 }) + (try ReadDigit('?') catch { _ => 0 })
        + (try ReadDigit('9') catch { _ => 0 });
    PrintLine("sum of 4?9 is {}", total);

    // The convenience has a price: the error is thrown away unseen. When the reason should
    // change what happens next, give `catch` one arm per case instead.
    return 0;
}

Run it

cd Examples/Errors/CatchFallback
rux run
volume 7, brightness 8, contrast 5
sum of 4?9 is 13

Common mistakes

Try it yourself

  1. Add up the digits '7', 'x' and '7' with a fallback of 0, then with a fallback of 5. Predict both sums.
  2. Write func Default() -> int that prints "(using the default)" and returns 5, and use it as the fallback for volume. When does the line appear?
  3. Rewrite brightness with one arm per case — Blank gives 8, NotADigit(_) gives 0.

Learn more