Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a basic classic try-catch in Zig

How do I implement the classic try-catch error handling in Zig?

For example. How to solve this error and only execute append when no error occurs?

var stmt = self.statement() catch {
    self.synchronize(); // Only execute this when there is an error.
};
self.top_level.statements.append(stmt); // HELP? This should only be executed when no error

// ...
fn synchronize() void {
  // ...implementation
}

fn statement() SomeError!void {
  // ...implementation
}

If possible please show a modified version of the above code.

like image 413
Himujjal Avatar asked Feb 20 '26 15:02

Himujjal


1 Answers

Try an if-else, as follows:

if (self.statement()) |stmt| {
   // HELP? This should only be executed when no error
   self.top_level.statements.append(stmt)
} else |error| {
  // Only execute this when there is an error.
  self.synchronize()
}

You can learn more about if in the zig documentation

like image 167
punkbit Avatar answered Feb 24 '26 01:02

punkbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!