# New to Zig. Having issues understanding the compiler warnings. (Error handling and function returns)

**URL:** <https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891>\
**Category:** Help\
**Tags:** language, compiler, error-handling\
**Created:** [November 16, 2024, 8:25pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891 "2024-11-16T20:25:40Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 8:25pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/1 "2024-11-16T20:25:40Z")

</div>

I’m relatively new to coding and I don’t have a CS or SE degree.  
I’ve written a program in C, then Rust and now I’m trying to write it in Zig.  
I really like how explicit you have to be with everything in Zig and it’s making me feel like I understand more about what the code is actually doing.  
However, I’ve been running into a lot of issues and I’m having trouble understanding the compiler.  
For this bit of the code, I basically want a function which I can use later to get input from the user and handle any errors.  
(I plan to do another function for string input later).  
Eventually the getUserInput() function will be used to navigate menus and enter in numbers for calculations.  
I think I have a poor understanding of error unions but maybe it’s more than that.

I’m sure this is a simple problem.  
But I’m at the point where I need to ask for help.  
How do I fix this? Also, what should I work on understanding for not being able to fix this myself.  
Here is an example of the code:

```zig
const std = @import("std");
const print = std.debug.print;

const InputError = error{
    EmptyInput,
};

const NumberError = error{
    InvalidCharacter,
    Overflow,
};

const ParseError = InputError || NumberError;

fn parseNumber(input_to_parser: []const u8) ParseError!u8 {
    if (input_to_parser.len == 0) return error.EmptyInput;
    return std.fmt.parseInt(u8, input_to_parser, 10);
}

fn getUserInput() !u8 {
    const stdin = std.io.getStdIn().reader();
    var input_buffer: [32]u8 = undefined;
    const user_input = try stdin.readUntilDelimiter(&input_buffer, '\n');

    if (parseNumber(user_input)) |number| {
        return number;
    } else |err| switch (err) {
        error.EmptyInput => print("Empty input not allowed!\n", .{}),
        error.InvalidCharacter => print("Invalid character!\n", .{}),
        error.Overflow => print("Overflow!\n", .{}),
    }
}

pub fn main() !void {
    // getUserInput()
    print("Enter a number: \n", .{});
    const user_selection = getUserInput();
    print("You've entered: {d}\n", .{user_selection});
}

```

---

<div class="post-metadata">

**Author:** ![pachde](https://ziggit.dev/user_avatar/ziggit.dev/pachde/32/2485_2.png) [@pachde](https://ziggit.dev/u/pachde)\
**Post date:** [November 16, 2024, 8:37pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/2 "2024-11-16T20:37:51Z")

</div>

What is it exactly that you need to fix? Please share, what compiler error your’e getting, if that is in fact what’s wrong.

BTW Zig compiler doesn’t do warnings. Only errors.

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 9:19pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/3 "2024-11-16T21:19:48Z")

</div>

I’m having a lot of trouble posting on this forum.  
I’m pretty sure those arrows didn’t print out correctly.

```zig
~/code/zig/ditmco2aas: zig run ditmco2aas.zig 
ditmco2aas.zig:20:20: error: function with non-void return type 'typeInfo(typeInfo(TypeOf
(ditmco2aas.getUserInput)).Fn.return_type.?).ErrorUnion.error_set!u8' implicitly returns
fn getUserInput() !u8 {
                   ^~
ditmco2aas.zig:32:1: note: control flow reaches end of body here
}
^
referenced by:
    main: ditmco2aas.zig:38:28
    callMain: /usr/lib/zig/std/start.zig:524:32
    remaining reference traces hidden; use '-freference-trace' to see all reference traces
/usr/lib/zig/std/fmt.zig:521:17: error: cannot format error union without a specifier (i.e. 
{!} or {any})
                compileError("cannot format error union without a specifier (i.e. {!} or {a
ny})");
                ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 ~~~~~~

```

---

<div class="post-metadata">

**Author:** ![squeek502](https://ziggit.dev/user_avatar/ziggit.dev/squeek502/32/409_2.png) [@squeek502](https://ziggit.dev/u/squeek502)\
**Post date:** [November 16, 2024, 9:37pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/4 "2024-11-16T21:37:35Z")

</div>

If the `else` branch in `getUserInput` is taken, no value is returned from the function, but you must return either a `u8` or an error.

---

<div class="post-metadata">

**Author:** ![permutationlock](https://ziggit.dev/user_avatar/ziggit.dev/permutationlock/32/9958_2.png) [@permutationlock](https://ziggit.dev/u/permutationlock)\
**Post date:** [November 16, 2024, 9:45pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/5 "2024-11-16T21:45:58Z")

</div>

To post code use three ``` characters at the start and end of the block, or just hit the `</>` “Preformatted text” button on the editor.

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 9:54pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/6 "2024-11-16T21:54:53Z")

</div>

I can’t even figure out how to properly do that.  
How do I print and return the error in a switch case statement?

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 9:55pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/7 "2024-11-16T21:55:37Z")

</div>

Thanks a lot! I wasn’t sure what “preformatted text meant”.

---

<div class="post-metadata">

**Author:** ![squeek502](https://ziggit.dev/user_avatar/ziggit.dev/squeek502/32/409_2.png) [@squeek502](https://ziggit.dev/u/squeek502)\
**Post date:** [November 16, 2024, 9:58pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/8 "2024-11-16T21:58:15Z")

</div>

Depends what you want to happen. Some options:

```zig
fn getUserInput() !u8 {
    // ...
    if (parseNumber(user_input)) |number| {
        return number;
    } else |err| {
        switch (err) {
            error.EmptyInput => print("Empty input not allowed!\n", .{}),
            error.InvalidCharacter => print("Invalid character!\n", .{}),
            error.Overflow => print("Overflow!\n", .{}),
        }
        // return the error we got from parseNumber
        return err;
    }
}

```

```zig
fn getUserInput() !u8 {
    // ...
    if (parseNumber(user_input)) |number| {
        return number;
    } else |err| switch (err) {
        error.EmptyInput => print("Empty input not allowed!\n", .{}),
        error.InvalidCharacter => print("Invalid character!\n", .{}),
        error.Overflow => print("Overflow!\n", .{}),
    }
    // return a default value
    return 0;
}

```

```zig
fn getUserInput() !u8 {
    // ...
    if (parseNumber(user_input)) |number| {
        return number;
    } else |err| switch (err) {
        error.EmptyInput => print("Empty input not allowed!\n", .{}),
        error.InvalidCharacter => print("Invalid character!\n", .{}),
        error.Overflow => print("Overflow!\n", .{}),
    }
    // return some other error
    return error.InvalidNumber;
}

```

You just need to return _something_, it’s up to you what gets returned and where.

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 10:24pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/9 "2024-11-16T22:24:24Z")

</div>

Interesting.  
Return err; gives me an LSP error "use of undeclared identifier ‘err’ ".

If I try " return 0" I get a compiler error.

```zig
~/code/zig/ditmco2aas: zig run ditmco2aas.zig 
/usr/lib/zig/std/fmt.zig:521:17: error: cannot format error union without a specifier (i.e. 
{!} or {any})
                @compileError("cannot format error union without a specifier (i.e. {!} or {a
ny})");
                ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 ~~~~~~
referenced by:
    format__anon_4002: /usr/lib/zig/std/fmt.zig:185:23
    print__anon_3623: /usr/lib/zig/std/io/Writer.zig:24:26
    remaining reference traces hidden; use '-freference-trace' to see all reference traces
~/code/zig/ditmco2aas:

```

I believe I get the same compiler error for trying "return error.InvalidCharacter.

---

<div class="post-metadata">

**Author:** ![squeek502](https://ziggit.dev/user_avatar/ziggit.dev/squeek502/32/409_2.png) [@squeek502](https://ziggit.dev/u/squeek502)\
**Post date:** [November 16, 2024, 10:49pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/10 "2024-11-16T22:49:12Z")

</div>

> [@Operator](#):
>
> Return err; gives me an LSP error "use of undeclared identifier ‘err’ ".

Double check you made the changes correctly. The `return err;` is _inside_ the `else` in that example.

> [@Operator](#):
>
> If I try " return 0" I get a compiler error.

You have to handle the possible error returned by `getUserInput` in `main`. The easiest way would be to use `try`:

```zig
    const user_selection = try getUserInput();

```

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 16, 2024, 11:10pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/11 "2024-11-16T23:10:14Z")

</div>

Thanks I didn’t realize the difference in syntax for some of your postings. I’m on a small laptop unfortunately.  
It’s working now!  
But I definitely need to understand errors better.  
I’ll most likely be able to reproduce the program I’ve written in C and rust now.

Do you have any suggestions?

Also, will returning the error always crash the program?  
If so, I may need to return -1. (0 or positive returns will be problematic)

---

<div class="post-metadata">

**Author:** ![squeek502](https://ziggit.dev/user_avatar/ziggit.dev/squeek502/32/409_2.png) [@squeek502](https://ziggit.dev/u/squeek502)\
**Post date:** [November 16, 2024, 11:35pm UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/12 "2024-11-16T23:35:24Z")

</div>

> [@Operator](#):
>
> will returning the error always crash the program?

Returning an error from `main` won’t crash the program. Try it out and see.

---

<div class="post-metadata">

**Author:** ![Operator](https://ziggit.dev/letter_avatar_proxy/v4/letter/o/f1d935/32.png) [@Operator](https://ziggit.dev/u/Operator)\
**Post date:** [November 17, 2024, 12:09am UTC](https://ziggit.dev/t/new-to-zig-having-issues-understanding-the-compiler-warnings-error-handling-and-function-returns/6891/13 "2024-11-17T00:09:20Z")

</div>

Nice.  
I do want the function to handle as much as possible though.

Thanks for your help squeek!
