Zig Error: expected error union type, found 'X'
error: expected error union type, found 'X' means you used try or catch on a value that can’t be an error. Both only work on error unions, the !T values returned by functions that can fail. Usually you either added try out of habit, or the value is an optional (?T), which uses orelse instead. For the other errors in this series, see Zig Errors Explained.
The error message
Section titled “The error message”const std = @import("std");
fn double(n: i32) i32 { return n * 2;}
pub fn main() !void { const x = try double(4); std.debug.print("{d}\n", .{x});}main.zig:8:25: error: expected error union type, found 'i32' const x = try double(4); ~~~~~~^~~main.zig:8:25: note: consider omitting 'try'found 'i32' is the type of what you put after try. double returns a plain i32: there’s no ! in its return type, so there’s no error to catch.
What it means
Section titled “What it means”try x is short for “if x is an error, return it; otherwise give me the value”. That only makes sense when x can be an error, so Zig checks the type. An error union is written E!T or just !T, like !i32 or error{OutOfMemory}!void. Anything else after try or before catch gets this error. The error union type section of the language reference explains the !.
Look at the found type to see what you really have:
| found | What it is | Fix |
|---|---|---|
'i32', 'void', '[]const u8'… |
A plain value | Remove try or catch |
'?u32' |
An optional | Use orelse or if |
How to fix it
Section titled “How to fix it”Fix 1: Remove the try
Section titled “Fix 1: Remove the try”If the function can’t fail, call it directly. That’s what the note suggests:
const std = @import("std");
fn double(n: i32) i32 { return n * 2;}
pub fn main() void { const x = double(4); std.debug.print("{d}\n", .{x});}Output:
8If nothing else in main uses try, you can also change !void back to void. Keeping !void isn’t an error, but it says main can fail when it can’t.
The same goes for catch. double(4) catch 0 gives the same message, without the note:
const std = @import("std");
fn double(n: i32) i32 { return n * 2;}
pub fn main() void { const x = double(4) catch 0; std.debug.print("{d}\n", .{x});}main.zig:8:25: error: expected error union type, found 'i32' const x = double(4) catch 0; ~~~~~~~~~~^~~~~~~Remove catch 0.
Fix 2: Use orelse for optionals
Section titled “Fix 2: Use orelse for optionals”This is the one that confuses people. A function that returns ?u32 can “fail” too, by returning null. But null isn’t an error, so try doesn’t apply:
const std = @import("std");
fn findAge(name: []const u8) ?u32 { if (std.mem.eql(u8, name, "Ada")) return 36; return null;}
pub fn main() !void { const age = try findAge("Ada"); std.debug.print("{d}\n", .{age});}main.zig:9:28: error: expected error union type, found '?u32' const age = try findAge("Ada"); ~~~~~~~^~~~~~~main.zig:9:28: note: consider omitting 'try'Here, “omitting try” alone isn’t enough: you’d get a ?u32 and still have to deal with the null. Optionals have their own tools. orelse gives a default, and orelse return error.X turns the null into an error, which is often what you wanted try to do:
const std = @import("std");
fn findAge(name: []const u8) ?u32 { if (std.mem.eql(u8, name, "Ada")) return 36; return null;}
fn ageOf(name: []const u8) !u32 { const age = findAge(name) orelse return error.NotFound; return age;}
pub fn main() void { const a = ageOf("Ada") catch 0; std.debug.print("Ada: {d}\n", .{a}); if (ageOf("Bob")) |b| { std.debug.print("Bob: {d}\n", .{b}); } else |err| { std.debug.print("Bob: {t}\n", .{err}); }}Output:
Ada: 36Bob: NotFoundageOf returns an error union, so catch and if ... else |err| work on it. Quick rule: ! goes with try and catch, ? goes with orelse and if. Zig Optionals and Zig Errors cover both.
Fix 3: Check the function’s current signature
Section titled “Fix 3: Check the function’s current signature”If the code came from a tutorial or an older project, the function may have changed between Zig versions. A call that used to return !T might return T now, or the other way round. Look at the real signature in your Zig’s standard library (in lib/std/ next to the zig binary, or with your editor’s “go to definition”) instead of trusting the example. The 0.17.0 release notes list what changed in the latest release.
Where you’ll usually see it
Section titled “Where you’ll usually see it”tryout of habit in front of every call, including ones that can’t fail.tryon lookups likemap.get(key), which returns?V, not!V.catchon an optional, likeitems.pop() catch .... Useorelse.- Copied code where the function’s return type has changed.
Related errors
Section titled “Related errors”- error union of type ‘X’ is ignored: the opposite, no
trywhere one is needed. - expected type ‘X’, found ‘Y’:
found '?u32'orfound '...!u32'when you store the result as a plain type. - attempt to use null value: what happens at runtime if you unwrap a
nullwith.?. - All Zig error pages: the full list.
Practice
Section titled “Practice”1. Look up a price
Section titled “1. Look up a price”priceOf should return the price, or the error UnknownItem for an unknown item. Fix it so the program prints apple: 3 and kiwi: UnknownItem.
const std = @import("std");
fn lookup(item: []const u8) ?u32 { if (std.mem.eql(u8, item, "apple")) return 3; return null;}
fn priceOf(item: []const u8) !u32 { return try lookup(item);}
pub fn main() void { for ([_][]const u8{ "apple", "kiwi" }) |item| { if (priceOf(item)) |p| { std.debug.print("{s}: {d}\n", .{ item, p }); } else |err| { std.debug.print("{s}: {t}\n", .{ item, err }); } }}Hint: lookup returns an optional. Which keyword turns null into an error?
Show solution
const std = @import("std");
fn lookup(item: []const u8) ?u32 { if (std.mem.eql(u8, item, "apple")) return 3; return null;}
fn priceOf(item: []const u8) !u32 { return lookup(item) orelse error.UnknownItem;}
pub fn main() void { for ([_][]const u8{ "apple", "kiwi" }) |item| { if (priceOf(item)) |p| { std.debug.print("{s}: {d}\n", .{ item, p }); } else |err| { std.debug.print("{s}: {t}\n", .{ item, err }); } }}Output:
apple: 3kiwi: UnknownItemlookup(item) orelse error.UnknownItem is either the price or the error, which is exactly what !u32 holds, so priceOf can return it directly.
tryandcatchonly work on error unions (!T).found 'i32'(or any plain type): the call can’t fail, so removetry/catch.found '?T': it’s an optional. Useorelseorif.orelse return error.Xturns anullinto an error.- If the code is copied, check the function’s current signature.
Next up: no field or member function named ‘x’, the error for a field or method that doesn’t exist.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Error union type in the Zig language reference: what
!Tis. - try in the Zig language reference: what
tryexpands to. - Optionals in the Zig language reference:
?T,orelseand.?. - Zig Try and Catch: our lesson on handling errors.