Back to course

Errors: The Error Set and Try

Full Course: Zig Programming From Zero to Hero

Error Handling in Zig

Zig uses error sets instead of exceptions. An error set is like an enum.

zig const FileError = error{ NotFound, AccessDenied, };

fn openFile(id: i32) FileError!void { if (id < 0) return FileError.NotFound; }

The try keyword

The try keyword is a shortcut to return an error if it occurs.

zig fn doWork() !void { try openFile(-1); }

It's equivalent to openFile(-1) catch |err| return err;.