#Exploring the Language: Error Handling

1 messages · Page 1 of 1 (latest)

crimson spruce
#

Hello all! I'm brand new here and to Zig.

I've built 0.14.0 from source for fun (since it sounds like a release is coming soon) and I've been playing around with things to get a feel for the language.

Right now I'm exploring error handling. Would this be considered idiomatic zig for dealing with custom error types or is there a more concise way to do this?

const std = @import("std");

pub const Error = error{
    InvalidValue,
};

const Person = struct {
    name: *const [50]u8,
    age: u8,

    pub fn init(n: *const [50]u8, a: u8) !Person {
        if (a > 100) return error.InvalidValue;
        return Person{ .name = n, .age = a };
    }

    pub fn do_stuff(p: Person) void {
        std.debug.print("Name: {s}\n", .{p.name}); 
        std.debug.print("Age: {}\n", .{p.age}); 
    }
};

pub fn main() void {
    if (Person.init("John Dork", 101)) |p| {
        p.do_stuff();
    } else |err| switch (err) {
        error.InvalidValue => std.debug.print("You died, your age needs to be > 100!", .{}),
    }
}
cold oasis
#

Yes, that's how error hanlding works in zig

cinder ingot
#

Where were you finding it verbose?

cold oasis
#

You might want to make init return Error!Person to typecheck returned errors

#

it's also possible to do:

const person = Person.init("John Dork", 101) catch |err| switch (err) {
  error.InvalidValue => {
    std.debug.print("You died, your age needs to be > 100!", .{});
    return;
  },
};
crimson spruce
#

How about if I would just like to error out here and print a custom message?

if (a > 100) return error.InvalidValue;

is there an option to do that? I was unable to find anything

crimson spruce
crimson spruce
#

let's say something akin to Rust's .expect("You did some bad stuff") panic messages

cold oasis
#

@panic

cinder ingot
#

Or std.debug.assert

cold oasis
#

you can also simply try foo(); but that will only print the error name

crimson spruce
#

Ok yeah guess I need to more closely review all of the builtins 😔

crimson spruce
#

Anything else error handling related in this context as far as builtins or otherwise?

I still need to explore the optionals

#

Eh I'll just keep reading along. Ty both very much for the information here!

cold oasis
crimson spruce
#

Yeah this is great. @cold oasis