Errors
An error set is like an enum (details on Zig’s enums later), where each error in the set is a value. There are no exceptions in Zig; errors are values. Let’s create an error set.
Error sets coerce to their supersets.
An error set type and another type can be combined with the !
operator to form
an error union type. Values of these types may be an error value or a value of
the other type.
Let’s create a value of an error union type. Here
catch
is used, which is
followed by an expression which is evaluated when the value preceding it is an
error. The catch here is used to provide a fallback value, but could instead be
a noreturn
- the type of
return
, while (true)
and others.
Functions often return error unions. Here’s one using a catch, where the |err|
syntax receives the value of the error. This is called payload capturing,
and is used similarly in many places. We’ll talk about it in more detail later
in the chapter. Side note: some languages use similar syntax for lambdas - this
is not true for Zig.
try x
is a shortcut for x catch |err| return err
, and is commonly used where
handling an error isn’t appropriate. Zig’s
try
and
catch
are unrelated to
try-catch in other languages.
errdefer
works like
defer
, but only executing
when the function is returned from with an error inside of the
errdefer
’s block.
Error unions returned from a function can have their error sets inferred by not having an explicit error set. This inferred error set contains all possible errors that the function may return.
Error sets can be merged.
anyerror
is the global error set, which due to being the superset of all error
sets, can have an error from any set coerced to it. Its usage should be
generally avoided.