<!-- Option, Result and ? · Tin · https://tin.ad/docs/learn/errors/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 7 of 34

# Option, Result and ?

**Goal.** Handle missing values and failures with `Option`, `Result` and `?`.

Tin has no `null` and no exceptions. Both are replaced by two ordinary sum types from the last
chapter, and you already know how to use those: with `match`.

## Maybe a value: Option

A function that may have nothing to give back returns `Option<T>`: `Some(value)`
or `None`.

*option.tin · tin run option.tin*

```tin
// Option<T> is Some(value) or None. There is no null.
fn findUser(id: int): Option<string> {
  if id == 1 { return Some("ada") }
  if id == 2 { return Some("grace") }
  None
}

fn main() {
  print(findUser(1))
  print(findUser(9))
  match findUser(2) {
    Some(name) => print("found {name}")
    None => print("no such user")
  }
}
```

<!-- output -->
```text
Some("ada")
None
found grace
```

An `Option<string>` is not a string. You can't use it as one by accident, which is the
mistake `null` lets you make:

*no-null.tin · tin check no-null.tin*

```tin
fn findUser(id: int): Option<string> {
  if id == 1 { return Some("ada") }
  None
}

fn main() {
  let name = findUser(1)
  print(name.upper())
}
```

<!-- compiler output -->
```text
error: no method 'upper' for Option<string>
 --> no-null.tin:8:9
  |
8 |   print(name.upper())
  |         ^^^^^^^^^^
  = note: 'upper' is a method of string, and this is an Option<string> that may not hold one
  = note: take the value out first: `match name { Some(v) => v.upper(), None => ... }`, `name.or(fallback).upper()`, or `?`
```

When there is an obvious default, `or` gives you the value or the fallback. The standard
`parseInt` returns an `Option`, because not every string is a number:

*or.tin · tin run or.tin*

```tin
fn main() {
  let port = parseInt("8080")      // parseInt returns an Option<int>
  let bad = parseInt("eighty")
  print(port)
  print(bad)
  print(port.or(80))               // the value, or a fallback
  print(bad.or(80))
  print(bad.isNone())
}
```

<!-- output -->
```text
Some(8080)
None
8080
80
true
```

## Success or failure: Result

When something can fail and the caller should know *why*, return `Result<T, E>`:
`Ok(value)` or `Err(error)`.

*result.tin · tin run result.tin*

```tin
// Result<T, E> is Ok(value) or Err(error): an operation that can fail, and why.
fn divide(a: int, b: int): Result<int, string> {
  if b == 0 { return Err("cannot divide {a} by zero") }
  Ok(a / b)
}

fn main() {
  print(divide(10, 2))
  print(divide(1, 0))
  match divide(7, 0) {
    Ok(n) => print("result: {n}")
    Err(why) => print("failed: {why}")
  }
}
```

<!-- output -->
```text
Ok(5)
Err("cannot divide 1 by zero")
failed: cannot divide 7 by zero
```

## Passing a failure up with ?

Often a function can't do anything useful about a failure, except pass it on to its caller. Writing a
`match` for that each time gets tedious, so Tin has `?`. Put it after a
`Result`: on `Ok` you get the value, and on `Err` the function returns that
error right away.

*question.tin · tin run question.tin*

```tin
fn parsePort(text: string): Result<int, string> {
  match parseInt(text) {
    Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
    None => Err("'{text}' is not a number")
  }
}

// ? takes the Ok value out, or returns the Err from this function right away.
fn address(host: string, port: string): Result<string, string> {
  let p = parsePort(port)?
  Ok("{host}:{p}")
}

fn main() {
  print(address("localhost", "8080"))
  print(address("localhost", "http"))
  print(address("localhost", "99999"))
}
```

<!-- output -->
```text
Ok("localhost:8080")
Err("'http' is not a number")
Err("port 99999 is out of range")
```

`?` works the same way on an `Option`, in a function that returns an
`Option`:

*question-option.tin · tin run question-option.tin*

```tin
// ? works on Option too, in a function that returns an Option.
fn sumOf(a: string, b: string): Option<int> {
  let x = parseInt(a)?
  let y = parseInt(b)?
  Some(x + y)
}

fn main() {
  print(sumOf("2", "40"))
  print(sumOf("2", "forty"))
}
```

<!-- output -->
```text
Some(42)
None
```

## Your own error types

A string explains a failure to a person. A sum type lets the code tell failures apart, and lets each
case carry details:

*own-error.tin · tin run own-error.tin*

```tin
// The error can be your own sum type, so callers can tell the failures apart.
type WithdrawError = | Insufficient { short: int } | Negative

fn withdraw(balance: int, amount: int): Result<int, WithdrawError> {
  if amount < 0 { return Err(Negative) }
  if amount > balance { return Err(Insufficient { short: amount - balance }) }
  Ok(balance - amount)
}

fn explain(e: WithdrawError): string => match e {
  Insufficient { short } => "not enough: {short} short"
  Negative => "amount can't be negative"
}

fn main() {
  for amount in [30, 500, -5] {
    match withdraw(100, amount) {
      Ok(left) => print("ok, {left} left")
      Err(e) => print(explain(e))
    }
  }
}
```

<!-- output -->
```text
ok, 70 left
not enough: 400 short
amount can't be negative
```

## When to panic

A *panic* stops the program. Tin panics on things that are bugs, not on things that can happen in
normal use: reading past the end of an array, integer overflow, dividing by zero.

*panic.tin · tin run panic.tin*

```tin
// panic is for bugs: things that should never happen. It stops the program.
fn main() {
  let scores = [90, 72, 85]
  print(scores[0])
  print(scores[3])          // there is no fourth score
}
```

<!-- output -->
```text
90
panic: index 3 is out of bounds for an array of length 3
```

A rule of thumb: if the caller could reasonably handle it (a missing file, a bad number from a
user, a model that answered nonsense), return a `Result`. If it means your program is wrong,
let it panic.

## Tasks

### Task 1: Safe division

Write `safeDivide(a: float, b: float): Option<float>` that returns `None` when
`b` is zero. Print it for 1/4 and 1/0, then 9/0 with a fallback of `0.0`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
fn safeDivide(a: float, b: float): Option<float> {
  if b == 0.0 { return None }
  Some(a / b)
}

fn main() {
  print(safeDivide(1.0, 4.0))
  print(safeDivide(1.0, 0.0))
  print(safeDivide(9.0, 0.0).or(0.0))
}
```

<!-- output -->
```text
Some(0.25)
None
0.0
```

### Task 2: Read a setting

Parse lines like `volume=7` into `Setting { key: string, value: int }`. Return
`Err` with a helpful message when there is no `=` or the value isn't a number.
Hint: `line.split("=")` gives you an array of the parts, and `parts.len` how many
there are.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```tin
type Setting = { key: string, value: int }

// "key=value", for example "volume=7"
fn parseSetting(line: string): Result<Setting, string> {
  let parts = line.split("=")
  if parts.len != 2 { return Err("expected key=value, got '{line}'") }
  match parseInt(parts[1]) {
    Some(n) => Ok(Setting { key: parts[0], value: n })
    None => Err("'{parts[1]}' is not a number")
  }
}

fn main() {
  print(parseSetting("volume=7"))
  print(parseSetting("volume"))
  print(parseSetting("volume=loud"))
}
```

<!-- output -->
```text
Ok(Setting { key: "volume", value: 7 })
Err("expected key=value, got 'volume'")
Err("'loud' is not a number")
```

### Task 3: Two numbers or nothing

Write `parsePoint(x: string, y: string): Result<(int, int), string>` using a helper that
turns `parseInt`'s `Option` into a `Result`, and `?` twice.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```tin
fn parsePoint(x: string, y: string): Result<(int, int), string> {
  let a = parseNumber(x)?
  let b = parseNumber(y)?
  Ok((a, b))
}

fn parseNumber(text: string): Result<int, string> {
  match parseInt(text) {
    Some(n) => Ok(n)
    None => Err("'{text}' is not a number")
  }
}

fn main() {
  print(parsePoint("3", "4"))
  print(parsePoint("3", "four"))
}
```

<!-- output -->
```text
Ok((3, 4))
Err("'four' is not a number")
```

## Recap

- There is no null: a value that may be missing is an `Option`.
- A call that can fail returns a `Result`; `?` passes the failure up.
- `panic` is for bugs, not for expected failures.

In the reference: [Option, Result and ?](https://tin.ad/docs/ref/language/#errors) · [Option and Result functions](https://tin.ad/docs/ref/stdlib/#core-types)
