在 Zig 中实现基本的经典 try-catch

问题描述

如何在 Zig 中实现经典的 try-catch 错误处理?

例如。如何解决这个错误,只在没有错误发生时才执行append

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-else,如下:

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()
}

您可以了解更多关于如果 in the zig documentation