A file reader can fail before it prints a byte: arguments may require memory, the file may be unreadable, and stdout may reject a write. Error handling makes those failure paths visible and gives the program a way to respond. section 3.4.1 section 3.4
In Zig, errors are values, and type-checked error sets describe possible failures. A return type such as !void means a function can return either an error or no value. Operations that may fail must be explicitly handled or propagated; try passes an error up the call stack. The syntax makes failure points easier to find without hiding them behind exceptions or raw error codes. section 1.6.2 section 3.4 section 3.4.1 section 1.2.3
Choose a response that fits the failure and the program:
- Propagate an unexpected error when stopping is acceptable, as with a rare stdout failure in a small command-line utility. section 3.4.1
- Turn a recoverable or user-facing failure into a readable message with hints for resolving it. section 3.4.1
- Log errors and continue when a long-running application needs to stay available. section 3.4.1
Listing 3.10 Cat errors
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena); #1
const cwd = std.Io.Dir.cwd();
const stdout_file = std.Io.File.stdout();
var stdout_buffer: [1024]u8 = undefined;
var stdout_writer = stdout_file.writer(io, &stdout_buffer);
const stdout = &stdout_writer.interface;
for (args[1..]) |filepath| {
const text = try cwd.readFileAlloc(
io,
filepath,
arena,
.unlimited,
); #2
try stdout.writeAll(text); #3
}
try stdout.flush(); #4
}
The cat utility marks argument allocation, file reading, writing, and flushing with try. Inspect the called functions’ error sets and standard library documentation to decide which failures deserve a more helpful response. section 3.4.1
An HTTP server needs a different policy. A non-POST request gets a 400 response; after that check, errdefer attempts a 500 response if request processing returns an error. errdefer runs only on an error return, and an error response can itself fail: the example catches and ignores that failure. Separating connection logic from error logging lets the server continue serving requests. section 4.2.4
Listing 4.13 Echo but web worthy
const std = @import("std");
fn handleConnection(io: std.Io, stream: std.Io.net.Stream) !void {
var stream_reader_buf: [1024]u8 = undefined;
var stream_writer_buf: [1024]u8 = undefined;
var stream_reader = stream.reader(io, &stream_reader_buf);
var stream_writer = stream.writer(io, &stream_writer_buf);
var http_server = std.http.Server.init( #1
&stream_reader.interface,
&stream_writer.interface,
);
var request = try http_server.receiveHead(); #2
if (request.head.method != .POST) { #3
request.respond("", .{ .status = .bad_request }) catch {};
return error.BadRequest;
}
errdefer request.respond("", .{ #4
.status = .internal_server_error,
}) catch {};
var reader_buf: [1024]u8 = undefined;
const reader =
try request.readerExpectContinue(&reader_buf); #5
const text = try reader.takeDelimiterExclusive(0); #6
var body_writer_buf: [1024]u8 = undefined;
var body_writer = try request.respondStreaming(&body_writer_buf, .{});
const body = &body_writer.writer; #7
try body.print("You said: {s}\n", .{text});
try body.flush();
try body_writer.end(); #8
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const addr = try std.Io.net.IpAddress.parse(
"127.0.0.1",
8000,
);
var tcp_server = try addr.listen(io, .{ .reuse_address = true });
defer tcp_server.deinit(io);
serve: while (true) {
const stream = tcp_server.accept(io) catch |e| {
std.log.err("accept: {}", .{e});
continue :serve;
};
defer stream.close(io);
handleConnection(io, stream) catch |e| { #9
std.log.err("handleConnection: {}", .{e});
};
}
}
Inspect the request-method check and errdefer in the HTTP handler: different failures call for different responses, and even the response may fail. section 4.2.4
At a C-compatible interface, idiomatic Zig error handling needs translation. One simple convention is a nullable pointer return: null represents a failed call. C does not enforce a single standard for representing errors, so the interface must choose its convention deliberately. section 5.4








