Pitch: `guard try` — error-aware early exit

To be clear, I don’t think we want to catch errors thrown in the else. But I also think easy to misinterpret the syntax as such. We have a do followed by a catch and only some parts of what’s in between is covered by the do-catch.

Maybe you see the else as a peer (like multiple catch at the same level are peers to each other), and I think it’s the pragmatic choice too, but I think interpreting the catch as applying to the block of code just above (that isn’t itself a catch) it is a valid to read it too. So it’s confusing. Hence why I think it’s better if the catch comes before the else.

Actually, I’d also change my suggestion above and move the do inside the condition to make it even clearer that the do-catch is solely applied to the condition:

guard do let x = try getOptionalX() catch {
  ... // error thrown, must exit scope
} else {
  ... // failed optional binding or condition, must also exit scope
}

And I’d make it work without the else for non-optional bindings:

guard do let x = try getX() catch {
  ... // error thrown, must exit scope
}

And I’d allow the same without the guard when there’s no binding and you can continue after the catch (same as what you suggested):

do doSomething() catch {
  ... // error thrown, but can continue in scope
}

I think this covers all bases.

So will it only catch errors thrown in expression, or will it also catch those thrown by the loop body? Personally, I’d expect errors in the loop body to be caught here, because the catch follows the loop body and it’s hard to see the loop body as a peer.

3 Likes