Skip to content

Errors As Values

Operations that can fail, such as reading a missing index, produce error values. try stops the function at an error value and returns it, so the function’s return type must allow err. catch replaces an error value with a fallback.

def first_plus_one(xs: list[num]) -> num | err:
first = try xs.get(0)
return first + 1
print(first_plus_one([7, 8]))
print(first_plus_one([]) catch -1)
Run in playground
Output
8
-1