Open-Source Zig Programming • OSZig.006 • 40–50 minutes
A configuration parser may encounter an invalid port number even when its own code is correct. Zig represents expected failure in a function’s return type. This lesson distinguishes error propagation, deliberate fallback and cleanup after failure. The example simulates local state and does not open a network socket.
Prerequisites and objectives
Review types and mutability, control flow, loops and arrays and slices. Use Zig 0.17.1, a text editor and a terminal. Identify an error set, unwrap an error union and distinguish error-only cleanup from normal scope-exit cleanup.
Error unions and explicit recovery
The Zig language reference defines error sets and error unions. PortError!u16 contains either a member of PortError or a successful unsigned 16-bit integer. An optional instead describes a value that can be absent. The try operator returns an error to the caller or unwraps the successful result. The catch operator allows local recovery or transformation of a failure. A fallback is a policy decision rather than a reason to hide every error.

Laboratory: validate and reserve a port
The reservation uses a Boolean to represent acquired state. The error-only deferred assignment releases that state if validation fails. Save the following as ports.zig:
const std = @import(“std”);
const PortError = error{InvalidPort};
fn port(n: u32) PortError!u16 {
if (n == 0 or n > 65535) return error.InvalidPort;
return @intCast(n);
}
fn checkedPort(n: u32) PortError!u16 {
return try port(n);
}
fn defaultPort(n: u32) u16 {
return port(n) catch 443;
}
fn reserve(n: u32, active: *bool) PortError!u16 {
active.* = true;
errdefer active.* = false;
return try port(n);
}
test “valid port” {
try std.testing.expectEqual(@as(u16, 8080), try checkedPort(8080));
}
test “invalid port propagates” {
try std.testing.expectError(error.InvalidPort, checkedPort(0));
try std.testing.expectError(error.InvalidPort, checkedPort(65536));
}
test “fallback” {
try std.testing.expectEqual(@as(u16, 443), defaultPort(0));
}
test “errdefer rolls back on failure only” {
var active = false;
try std.testing.expectError(error.InvalidPort, reserve(0, &active));
try std.testing.expect(!active);
_ = try reserve(8080, &active);
try std.testing.expect(active);
}
Execute the four native test blocks with this command:
zig test ports.zig
Expected behavior: accept 8080, reject zero and 65536, fall back to 443, and undo the reservation only on failure. Zero is disallowed by this application’s policy; some real socket APIs use zero to request an automatically assigned port. A production application must choose its own validation policy.
Reference-model verification
Six independent behavioral checks passed in a Python 3.13.5 model: acceptance of 8080, rejection of zero, rejection of 65536, fallback to 443, failed-reservation cleanup and successful-reservation preservation. Python exceptions simulate the expected behavior but are not Zig error unions. Native Zig compilation was unavailable; the four native test blocks remain unexecuted.
Knowledge check
What happens after a failed try? The caller receives the error. When does errdefer run? On the error exit path of its scope. How does defer differ? It also runs on normal scope exit. Why not always use catch with a default? A substituted value may hide a configuration failure that the caller needs to address. Before deployment, execute the native tests and add boundaries appropriate to the application.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply