Skip to content

Commit ecdfdcc

Browse files
committed
add error
1 parent 31408eb commit ecdfdcc

File tree

6 files changed

+111
-0
lines changed

6 files changed

+111
-0
lines changed

error/basic.zig

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const print = @import("std").debug.print;
2+
3+
const MyError = error{
4+
OutOfRange,
5+
NotFound,
6+
};
7+
8+
pub fn main() void {
9+
const err: MyError = MyError.OutOfRange;
10+
print("{}", .{err});
11+
}

error/merged.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const print = @import("std").debug.print;
2+
3+
const AError = error{
4+
ErrorA1,
5+
ErrorA2,
6+
};
7+
8+
const BError = error{
9+
ErrorB1,
10+
ErrorB2,
11+
};
12+
13+
const CError = AError || BError;
14+
15+
pub fn main() void {
16+
const err1: CError = CError.ErrorA1;
17+
const err2: CError = CError.ErrorB2;
18+
print("{}, {}", .{ err1, err2 });
19+
}

error/payload.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const print = @import("std").debug.print;
2+
3+
const MyError = error{
4+
OutOfRange,
5+
NotFound,
6+
};
7+
8+
pub fn main() void {
9+
const value = do_something() catch |err| {
10+
print("Error: {}\n", .{err});
11+
return;
12+
};
13+
print("Value: {}\n", .{value});
14+
}
15+
16+
fn do_something() MyError!u8 {
17+
return MyError.OutOfRange;
18+
// return 1;
19+
}

error/readme.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Errors
2+
3+
```bash
4+
$ zig run basic.zig
5+
error.OutOfRange
6+
```
7+
8+
```bash
9+
$ zig run superset.zig
10+
Yes
11+
```
12+
13+
```bash
14+
$ zig run merged.zig
15+
error.ErrorA1, error.ErrorB2
16+
```
17+
18+
```bash
19+
$ zig run union.zig
20+
Value: 32
21+
Value: 0
22+
```
23+
24+
```bash
25+
$ zig run payload.zig
26+
Error: error.OutOfRange
27+
```

error/superset.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const print = @import("std").debug.print;
2+
3+
const AError = error{
4+
Error1,
5+
Error2,
6+
};
7+
8+
const BError = error{
9+
Error1,
10+
};
11+
12+
pub fn main() void {
13+
const err_a = AError.Error1;
14+
const err_b = BError.Error1;
15+
16+
if (err_a == err_b) {
17+
print("Yes", .{});
18+
}
19+
}

error/union.zig

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const print = @import("std").debug.print;
2+
3+
const MyError = error{
4+
OutOfRange,
5+
NotFound,
6+
};
7+
8+
pub fn main() void {
9+
var value: MyError!u8 = 32;
10+
var unwrap = value catch 0;
11+
print("Value: {}\n", .{unwrap});
12+
13+
value = MyError.OutOfRange;
14+
unwrap = value catch 0;
15+
print("Value: {}", .{unwrap});
16+
}

0 commit comments

Comments
 (0)