2

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.

Himujjal
  • 1,581
  • 1
  • 14
  • 16

1 Answers1

5

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

punkbit
  • 7,347
  • 10
  • 55
  • 89