Skip to content

Zig Try & Catch

In Zig Errors you saw that a function that can fail returns an error union, and that you must unwrap it before you can use the value. In real code you’ll do that dozens of times per file, so Zig gives you two short keywords for it. try says “if this failed, I can’t deal with it here, pass the error to my caller”. catch says “if this failed, here’s what to do instead”. Almost all error handling in Zig is one of those two.

Most of the time, a function can’t fix a problem it runs into. A function that reads an age from text can’t invent a valid age when the text is "abc". The honest thing is to give the error back to whoever called it. That’s try:

const std = @import("std");
fn parseAge(text: []const u8) !u8 {
const age = try std.fmt.parseInt(u8, text, 10);
if (age > 150) return error.TooOld;
return age;
}
pub fn main() void {
const inputs = [_][]const u8{ "42", "abc", "200", "999" };
for (inputs) |text| {
if (parseAge(text)) |age| {
std.debug.print("{s}: age {d}\n", .{ text, age });
} else |err| {
std.debug.print("{s}: {t}\n", .{ text, err });
}
}
}

Output:

42: age 42
abc: InvalidCharacter
200: TooOld
999: Overflow

std.fmt.parseInt(u8, text, 10) turns text into a u8 (the 10 means base 10). It returns an error union, because the text might not be a number (error.InvalidCharacter) or might be too big for a u8 (error.Overflow).

try in front of it does two things:

  • If parsing worked, try unwraps the value, so age is a plain u8.
  • If it failed, try returns that error from parseAge right away. The lines after it don’t run.

So parseAge can now fail in three ways: the two from parseInt, plus its own error.TooOld. Because its return type is !u8, Zig adds them all to its inferred error set for you.

Since try returns the error, the function it’s in has to be allowed to return errors. In a function returning plain void, it doesn’t compile:

const std = @import("std");
pub fn main() void {
const n = try std.fmt.parseInt(u32, "42", 10);
std.debug.print("{d}\n", .{n});
}
main.zig:4:15: error: expected type 'void', found 'error{InvalidCharacter,Overflow}'
const n = try std.fmt.parseInt(u32, "42", 10);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.zig:3:15: note: function cannot return an error
pub fn main() void {
^~~~

The note says it plainly: “function cannot return an error”. You have two fixes. Change the return type to !void (for main, that’s fine: an error that reaches the top is printed, see Zig Errors), or handle the error right here with catch.

You’ve already seen the simplest catch: a value to use if something failed.

const std = @import("std");
pub fn main() void {
const width = std.fmt.parseInt(u32, "80", 10) catch 100;
const height = std.fmt.parseInt(u32, "tall", 10) catch 100;
std.debug.print("{d} x {d}\n", .{ width, height });
}

Output:

80 x 100

This is great when there’s a sensible default, like a window size or a setting that’s allowed to be missing. The fallback must have the same type as the value: catch "none" after a u32 won’t compile (“incompatible types”).

Sometimes you want to do more than pick a value: print a warning, count failures, then carry on. Put a block after catch. Write |err| to get the error, and use a labeled block (blk: … break :blk value) to hand a value back:

const std = @import("std");
pub fn main() void {
const text = "12x";
const count = std.fmt.parseInt(u32, text, 10) catch |err| blk: {
std.debug.print("could not read '{s}' ({t}), using 1\n", .{ text, err });
break :blk 1;
};
std.debug.print("count: {d}\n", .{count});
}

Output:

could not read '12x' (InvalidCharacter), using 1
count: 1

Labeled blocks were covered in Zig Blocks. Here, break :blk 1; ends the block and makes 1 the result of the whole catch.

The block can also leave instead of giving a value: return, continue or break all work inside it. That’s often the cleanest choice in loops: “if this line is bad, skip to the next one”.

catch |err| switch (err): one plan per error

Section titled “catch |err| switch (err): one plan per error”

Different errors often need different answers. Combine catch with a switch on the error:

const std = @import("std");
pub fn main() void {
const inputs = [_][]const u8{ "42", "abc", "300", "-1" };
for (inputs) |text| {
const n = std.fmt.parseInt(u8, text, 10) catch |err| switch (err) {
error.InvalidCharacter => {
std.debug.print("{s}: not a number\n", .{text});
continue;
},
error.Overflow => {
std.debug.print("{s}: doesn't fit in a u8\n", .{text});
continue;
},
};
std.debug.print("{s}: {d}\n", .{ text, n });
}
}

Output:

42: 42
abc: not a number
300: doesn't fit in a u8
-1: doesn't fit in a u8

Notice there’s no else in this switch. parseInt has an exact error set, error{ InvalidCharacter, Overflow }, and we handled both, so Zig knows the switch is complete. If a future Zig version added a third error to parseInt, this code would stop compiling and point you to the new case. That’s the big win of switching on errors: you can’t forget one.

(Also notice "-1" gives Overflow, not InvalidCharacter. A u8 can’t be negative, so parseInt counts it as “outside the range”. Little surprises like this are why it’s worth printing the error name while you develop.)

Prongs can also list a name that isn’t in the set by mistake. Zig catches that too:

const std = @import("std");
fn check(n: i32) !void {
if (n < 0) return error.Negative;
}
pub fn main() void {
check(-1) catch |err| switch (err) {
error.Negative => std.debug.print("negative\n", .{}),
error.TooBig => std.debug.print("too big\n", .{}),
};
}
main.zig:10:9: error: expected type '@typeInfo(@typeInfo(@TypeOf(main.check)).@"fn".return_type.?).error_union.error_set', found 'error{TooBig}'
error.TooBig => std.debug.print("too big\n", .{}),
^~~~~~~~~~~~
main.zig:10:9: note: 'error.TooBig' not a member of destination error set

Often you know how to deal with one error but not the others. Handle that one, and send the rest up with else => |e| return e:

const std = @import("std");
fn readPort(text: []const u8) !u16 {
const port = std.fmt.parseInt(u16, text, 10) catch |err| switch (err) {
error.InvalidCharacter => return error.NotANumber,
error.Overflow => return error.OutOfRange,
};
if (port == 0) return error.OutOfRange;
return port;
}
fn portOrDefault(text: []const u8) !u16 {
return readPort(text) catch |err| switch (err) {
error.OutOfRange => 8080,
else => |other| return other,
};
}
pub fn main() void {
const inputs = [_][]const u8{ "3000", "0", "99999", "http" };
for (inputs) |text| {
std.debug.print("{s}: {!d}\n", .{ text, portOrDefault(text) });
}
}

Output:

3000: 3000
0: 8080
99999: 8080
http: error.NotANumber

Two things happen here:

  • readPort translates errors. InvalidCharacter and Overflow are details of how parsing works. Callers care about “that wasn’t a number” and “that’s not a valid port”, so readPort returns its own, clearer errors.
  • portOrDefault recovers from one error (a bad range gets the default port 8080) and passes every other error on unchanged with else => |other| return other.

This is how errors usually move through a real program: each layer handles what it understands and passes on the rest.

catch unreachable: “this can’t fail”

Section titled “catch unreachable: “this can’t fail””

Sometimes you know an error can’t happen, but the function’s type says it might. For example, parsing a number you wrote yourself:

const std = @import("std");
pub fn main() void {
const default_size = std.fmt.parseInt(u32, "64", 10) catch unreachable;
std.debug.print("size: {d}\n", .{default_size});
}

Output:

size: 64

catch unreachable tells Zig “an error here would be a bug”. It’s like the else => unreachable from Zig Unreachable. And it has the same risk: if you’re wrong, a debug or safe build stops with a panic. Here the input contains a typo, the letter O instead of a zero:

const std = @import("std");
pub fn main() void {
const sizes = [_][]const u8{ "10", "20", "3O" };
var total: u32 = 0;
for (sizes) |s| {
total += std.fmt.parseInt(u32, s, 10) catch unreachable;
}
std.debug.print("total: {d}\n", .{total});
}

You’ll see something like:

thread 1029 panic: attempt to unwrap error: InvalidCharacter
error return context:
std/fmt.zig:583:24: 0x10f4e5a in charToDigit (std.zig)
if (value >= base) return error.InvalidCharacter;
^
...
stack trace:
main.zig:7:53: 0x11e3e85 in main (main.zig)
total += std.fmt.parseInt(u32, s, 10) catch unreachable;
^

The panic names the error (InvalidCharacter), shows where inside the standard library it came from (“error return context”), and then the line in your code that said it couldn’t happen. In fast and small builds there’s no check at all, and the program just carries on with whatever garbage it has. That’s why catch unreachable belongs only on things that are truly fixed in your code, never on user input, files or anything from the network.

Once in a while an error really doesn’t matter. Say you print a “goodbye” message as the program closes: if that fails, there’s nothing useful left to do. Write catch {}:

const std = @import("std");
fn sayGoodbye(loud: bool) !void {
if (!loud) return error.TooQuiet;
std.debug.print("GOODBYE!\n", .{});
}
pub fn main() void {
sayGoodbye(true) catch {};
sayGoodbye(false) catch {};
std.debug.print("done\n", .{});
}

Output:

GOODBYE!
done

This works for !void functions: {} is an empty block, which has the type void, the same as the missing value. Use it sparingly. Every catch {} is a place where a problem disappears without a trace, so a short comment saying why it’s safe is a kind thing to leave for the next reader.

You want to Write
Let the caller deal with it try thing()
Use a default value thing() catch 0
Log it, then use a value thing() catch |err| blk: { ...; break :blk 0; }
Skip this item in a loop thing() catch continue
Do something different per error thing() catch |err| switch (err) { ... }
Run different code for success and failure if (thing()) |v| { ... } else |err| { ... }
Say “this can never fail” thing() catch unreachable
Ignore a failure on purpose thing() catch {}

When in doubt, start with try. Pass errors up until you reach a place that knows what to do about them, often close to main or the code that talks to the user. The language reference on catch and on try has the official description of both.

Given const items = [_][]const u8{ "5", "x", "10", "", "20" };, add up only the items that parse as a u32, skipping the rest. Print the total.

Hint: catch continue skips to the next round of the loop.

Show solution
const std = @import("std");
pub fn main() void {
const items = [_][]const u8{ "5", "x", "10", "", "20" };
var total: u32 = 0;
for (items) |item| {
const n = std.fmt.parseInt(u32, item, 10) catch continue;
total += n;
}
std.debug.print("total: {d}\n", .{total});
}

Output:

total: 35

"x" and "" both fail to parse, so catch continue jumps to the next item for them. An empty string is an error too (InvalidCharacter), which is easy to forget.

Write fn area(w_text: []const u8, h_text: []const u8) !u32 that parses both strings with try and returns their product. In main, print area("3", "4") and area("3", "four") with {!d}.

Hint: two try lines, one for each number. main doesn’t need try if you print with {!d}.

Show solution
const std = @import("std");
fn area(w_text: []const u8, h_text: []const u8) !u32 {
const w = try std.fmt.parseInt(u32, w_text, 10);
const h = try std.fmt.parseInt(u32, h_text, 10);
return w * h;
}
pub fn main() void {
std.debug.print("{!d}\n", .{area("3", "4")});
std.debug.print("{!d}\n", .{area("3", "four")});
}

Output:

12
error.InvalidCharacter

The second call fails at the second try, so area returns error.InvalidCharacter and the multiplication never runs.

Write fn describe(text: []const u8) []const u8 that returns "ok" if text parses as a u8, "please type digits only" for InvalidCharacter, and "please use 0 to 255" for Overflow. Use catch |err| switch (err) with no else.

Hint: each prong can return a string straight from describe.

Show solution
const std = @import("std");
fn describe(text: []const u8) []const u8 {
_ = std.fmt.parseInt(u8, text, 10) catch |err| switch (err) {
error.InvalidCharacter => return "please type digits only",
error.Overflow => return "please use 0 to 255",
};
return "ok";
}
pub fn main() void {
std.debug.print("{s}\n", .{describe("7")});
std.debug.print("{s}\n", .{describe("seven")});
std.debug.print("{s}\n", .{describe("700")});
}

Output:

ok
please type digits only
please use 0 to 255

describe returns a plain []const u8, not an error union: it turns every error into a message, so its callers have nothing left to handle. We don’t need the number itself, so _ = throws it away after the catch has dealt with the error.

  • try x unwraps the value or returns the error from the current function. It’s short for x catch |err| return err.
  • try only works in a function whose return type can hold the error, like !void or !u8.
  • catch value gives a fallback. catch |err| blk: { ... } runs code and can still give a value.
  • catch |err| switch (err) handles each error separately, and Zig checks you’ve covered all of them.
  • Handle what you understand and pass on the rest with else => |e| return e.
  • catch unreachable is for errors that would be bugs. It panics in debug/safe and isn’t checked in fast/small.
  • catch {} ignores an error on purpose. Use it rarely, and say why.

Next up: Zig Errdefer, cleanup code that runs only when a function fails.

Quick check

1. What does const n = try parse(text); do if parse returns an error?
2. Why does try in pub fn main() void fail to compile?
3. You handle both errors of parseInt in a catch |err| switch (err) with no else. What happens if a new error is added to parseInt later?
4. When is catch unreachable a good choice?