Error Handling in Zig
Zig treats errors as values, the far superior method (subjectively). An error as a value is predictable and explicit, as opposed to the devil that is handling exceptions. It means that simply by looking at a function signature the caller can determine something can go wrong, and decide, at that point in time, how to handle the problem. Let’s look at some ways to handle errors in zig.
The Try
fn main() !void {
const file = try std.fs.cwd().openFile("input.txt", .{});
}
The Catch
fn main() void {
const file = std.fs.cwd().openFile("input.txt", .{}) catch {
std.debug.print("file not found\n", .{});
std.process.exit(1);
};
}
The Catch Switch
fn main() void {
const file = std.fs.cwd().openFile("input.txt", .{}) catch |err| switch |err| {
error.FileNotFound => {
std.debug.print("file not found\n", .{});
std.process.exit(1);
},
else => {
std.debug.print("you're on your own\n", .{});
std.process.exit(2);
}
};
}
The Catch Panic
fn main() !void {
const file = std.fs.cwd().openFile("input.txt", .{}) catch @panic("out of memory");
}
The Catch Unreachable (C like behavior)
fn main() void {
const file = std.fs.cwd().openFile("input.txt", .{}) catch unreachable;
}
The Catch Return (C like behavior)
fn main() u8 {
const file = std.fs.cwd().openFile("input.txt", .{}) catch return 1;
}