---
title: "Failures"
url: https://una-lang.org/en/docs/guides/failures/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/guide/una-for-agents.md
---

# Failures

Errors are values of a sum kind. A function declares at most one, `fails E`, and ends with `fail V(...)`. Every statement that can fail is handled on the lines below it, or wrapped in `attempt`:

| Clause | Meaning |
| --- | --- |
| `if error fail V(...)` | any failure becomes `V`; `error` names the original |
| `if error pass` | propagate unchanged; the callee's error kind is the function's |
| `if error use e` | recover with the value `e` |
| `if none fail V(...)` | `None` becomes `V`, and the statement's value is the payload |
| `if none use e` | `None` becomes `e` |

One effect per line: a capability operation, or a call of a function that has `uses` or `fails`, is the whole expression of its statement, `let` or final expression. `attempt f(x)` turns a failure into `Err`, so the result is a `Result`; when it is `Ok`, the callee's `ensures` hold for the value.

```una
module demo

pub kind Oops = | TooLarge

pub bump(n: Int) -> Int
  ensures result > n
  fails Oops
=
  if n > 100 then fail TooLarge else n + 1

pub bump_twice(n: Int) -> Int
  fails Oops
=
  let once = bump(n)
    if error pass
  bump(once)
    if error pass

pub bump_or_same(n: Int) -> Int
  ensures result >= n
=
  let outcome = attempt bump(n)
  when outcome
    is Ok(value) -> value
    is Err -> n
```

An arm of `when` or a branch of `if` may `fail`, so a binding takes the value of the arms that do not:

```una
module demo

pub kind Unreadable = | NotANumber

--- The integer a JSON value holds.
pub number(j: Json) -> Int
  fails Unreadable
=
  let n = when j
    is Number(value) -> value
    else -> fail NotANumber
  n
```

```una
-- fails with U3007
module demo

pub kind Oops = | TooLarge

pub bump(n: Int) -> Int
  fails Oops
=
  if n > 100 then fail TooLarge else n + 1

pub bump_twice(n: Int) -> Int
  fails Oops
=
  let once = bump(n)
  bump(once)
    if error pass
```

```una
-- fails with U3013
module demo

capability Clock
  op now() -> Int

pub later() -> Int
  uses @clock: Clock[now]
=
  1 + @clock.now()
```
