#Zigglings - Quizz 4 - try catch

1 messages · Page 1 of 1 (latest)

craggy storm
#

Hi,

Here is my code :

const std = @import("std");

const NumError = error{IllegalNumber};

pub fn main() void {
    //const stdout = std.io.getStdOut().writer();

    const my_num: u32 = getNumber() catch 42;

    //try stdout.print("my_num={}\n", .{my_num});
    std.debug.print("my_num is: {}\n", .{my_num});
}

// This function is obviously weird and non-functional. But you will not be changing it for this quiz.
fn getNumber() NumError!u32 {
    if (false) return NumError.IllegalNumber;
    return 42;
}```

It works.

However, when trying with stdout instead of debug.print, it throws the following errror :

exercises/034_quiz4.zig:17:5: error: expected type 'void', found 'error{AccessDenied,Unexpected,DiskQuota,FileTooBig,InputOutput,NoSpaceLeft,DeviceBusy,InvalidArgument,BrokenPipe,SystemResources,OperationAborted,NotOpenForWriting,LockViolation,WouldBlock,ConnectionResetByPeer}'
try stdout.print("my_num={}\n", .{my_num});
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
exercises/034_quiz4.zig:12:15: note: function cannot return an error
pub fn main() void {
^~~~
referenced by:
callMain: /snap/zig/8241/lib/std/start.zig:564:17
initEventLoopAndCallMain: /snap/zig/8241/lib/std/start.zig:508:34
remaining reference traces hidden; use '-freference-trace' to see all reference traces

I can't figure out why the compiler says the stdout.print problem would throw an error, since I am giving a default value to my_num with `catch`... can someone explain it to me ? ^^

Thank you !!
gentle seal
#

that error means the return type of main() doesn't match the error union which stdout.print() may return. in this case, your main returns type void. however try stdout.print() may return all those errors in the error message. does that make sense? i know this can be a confusing error message at first.

#

in order to fix it, you can change the return type of main to main() !void

mossy trellis
#

This indeed is the key part there:

exercises/034_quiz4.zig:12:15: note: function cannot return an error
pub fn main() void {
              ^~~~