[Pitch] `guard do ... catch`: local error handling with early-exit and bound variables

Motivation

It is a common pattern to have a throwing function whose result needs to be bound for use in the enclosing scope.

let value = try thrower()
// We want to handle any thrown errors and exit early
// so that the value binding can stay un-nested.
use(value)

There are a few ways to achieve this today, none of which are ideal.

do/catch

The do/catch versions have multiple issues:

do {
    let value = try thrower()
    use(value) // The happy path is nested
} catch {
    // Error handling is visually separated from the point
    // of origin of the error in code,  especially when the
    // happy path is particularly long.
    log(error)
    return
}

Wrapping more code in the do also widens what the catch handles: a throw from use(value) is caught by the same block, even if that was not intended. There is a better version, but that has its own issues:

// Declaration is split from initialization
let value: Value // A type annotation becomes necessary
do {
    value = try thrower()
} catch {
    log(error)

    // Unlike guard statements, do statements aren't generally
    // associated with early exit, so its harder to visually
    // verify that the code indeed exits early when it should.
    return
}

use(value)

try?

Alternatively, try? allows a concise guard statement, which is the idiomatic way to bind a conditionally existing value, with early exit on failure. However, it loses information on the error value itself.

guard let value = try? thrower() else {
    // The error value is lost so no specialized error
    // handling is possible.
    return
}

Result

Result avoids the nesting and keeps the error, but it needs a wrapper at the call site and a second pattern match to retrieve the error.

// A Result {} wrap becomes necessary at the call point.
// Combined with the .success pattern matching, it is a lot of
// ceremony for such a common use case.
//
// The binding also needs to be separate from the guard to allow
// pattern matching twice, once for the value and once for the
// error, though this is mostly down to code preference.
let result = Result { try thrower() }
guard case let .success(value) = result else {
    // A second pattern match is required to retrieve the error,
    // even though failure of the .success pattern guarantees it.
    if case let .failure(error) = result {
        log(error)
    }

    return
}

use(value)

The issue is so common that there has been a whole history of pitches/discussions trying to solve this very issue. This pitch takes design elements/inspiration and incorporates feedback from all of these:

  • Extend "guard" to try-statements, with a catch block (2016). First proposed guard let x = try foo catch { ... }. Chris Lattner objected that guard let must keep meaning "match an optional" and that try already means "propagate", so a later catch should change neither. He suggested putting the behavior on the binding (let x = try foo() catch { ... }), with else plus catch for optional-returning throwers, both required to exit. Jordan Rose suggested guard try let x = foo() catch, noting that try cannot be limited to part of the expression. This pitch leaves let and try unchanged and gives the new meaning to a separate do marker.
  • Guard/Catch (2017) and its written proposal. It was submitted as a formal proposal but closed after core team pre-review. The core team agreed the problem is worth solving, but considered it unacceptable for the meaning of guard let x = ... to depend on whether else or catch follows, and noted that building this into guard implies an if equivalent. The authors had also set aside combining catch with else, since it raised unanswered questions about the bound type, clause order, and whether else may sit between catch clauses. This pitch addresses these with a separate do marker, so guard let and try are unchanged.
  • Is it possible to make early exit in do-try-catch block? (2019). Participants proposed guard/catch and a guard-like do-guard let a = try f(), let b = try g() catch { ... }. One contributor proposed requiring catch when any condition uses try and else when any condition unwraps or tests. This pitch uses the same rule, keyed on an explicit do marker so that a plain try condition still propagates. The thread also warned that letting an unmatched error fall through to else would swallow it, so unmatched errors propagate here instead.
  • Guard-like syntax for do/catch (2021). Proposed do let value = try f() catch { ... }, guard with else and catch, and a value-returning do.
  • Guard-Let-Catch (and If-Let-Catch) (2023). Proposed catch on guard/if whenever the condition contains try. Replies noted that do expression branches cannot return, and asked how to tell which of several statements failed.
  • Introducing do-let-catch (Oct 2024). Proposed do let (data, response) = try await ... catch { throw ... }, without guard. A reply argued that a do/catch variant should not force early exit, and another showed that do expressions cover the case where the catch rethrows. This pitch keeps guard so that exit is guaranteed.
  • Guard that works with 'try' (Jun 2025). Proposed guard let x = try f() else { ... } with an implicit error; replies objected that this conflicts with optional unwrapping.
  • Un-nesting the happy path when catching errors (Feb 2026). Proposed a trailing expr catch { ... }, braceless do try ... catch, do/catch expressions, and guard try let x = f() else { ... }.
  • Pitch: guard try (Mar 2026). Proposed separate else and catch blocks on guard, with no marker. Replies proposed a braceless do guard, a braced guard do { ... } catch { ... }, and do/catch expressions. Michel Fortin's reply placed a do marker inside the condition, the closest prior art for this pitch.

The motivation this proposal sets out with is a clean way to bind variables to throwing functions, and handling any errors in place with early exit guarantees.

Proposal

We introduce a new do marker for guard conditions. Errors thrown by a do-marked condition are caught by the catchblocks of the guard.

guard do let value = thrower() catch {
    // Implicit error variable as in catch blocks
    log(error)
    return
}

// guard guarantees exit on error so value is bound
// in the non-nested scope; traditional guard behavior.
use(value)

A do let condition is a plain binding. No optional unwrapping or condition check is performed, so if thrower()returns Int?, then value is an Int?, and a nil result is a success. This is similar to how the case marker already behaves.

Rules

  • Marking a non-throwing expression as do is a "guard condition is always true" warning.
  • A guard containing any do condition requires at least one catch block. If there are no do conditions, having catch blocks is a dead code warning.
  • A guard containing any non-do condition requires an else block. If there are no non-do conditions, having an else block is a dead code warning.
  • catch blocks, just like else blocks, must exit the current scope. catch and else blocks may be written in either order, and the order does not change their meaning.
  • catch blocks handle errors thrown by do conditions only. A try anywhere else in the guard propagates as it does today, and errors thrown from inside an else or catch body also propagate.
  • Bindings introduced by the guard are not in scope inside its catch and else blocks, as with guard today.
  • Mixed markers like do case let are beyond the scope of this pitch.

Since do can only mark throwing expressions, the try annotation becomes redundant and can be skipped.

Just like in traditional do statements, catch blocks following a guard can be multiple in number and support all the relevant pattern matching. Also like traditional do statements, the catch blocks need not be exhaustive. Any uncaught error propagates, and error propagation exits the current scope, preserving the guarantee of guard. The enclosing context must be able to throw in that case, the same check do/catch performs today.

guard do let value = anyErrorThrower()
  catch is Error1 {
    return
} // Any other error propagates, exiting the current scope

use(value)

Type inference for the implicit error variable is the same as in do statements.

// Same type inference as catch blocks in `do` bodies.
guard do let value = error1Thrower() catch {
    // error: Error1 with FullTypedThrows feature flag
    // error: any Error otherwise
    return
}

guard do let value1 = error1Thrower(),
      do let value2 = error2Thrower() catch {
    // error: any Error
    return
}

Mixing with other conditions

As with other guard patterns, do can be used in tandem with other conditions, so catch and else blocks may co-exist.

guard do let value1 = error1Thrower(),
      do let value2 = error2Thrower(),
         let value3 = try throwingOptionalReturner(),
      boolReturner()
catch let error as Error1 {
    // error1Thrower() threw.
    log(error)
    return
} catch {
    // Handles any other error from a `do` condition. If this
    // block is removed, unhandled errors propagate.
    // Errors from `try throwingOptionalReturner()` never get
    // here since that condition is not marked `do`.
    return
} else {
    // One of the non-`do` conditions failed:
    // `try throwingOptionalReturner()` returned nil, or
    // `boolReturner()` returned false.
    return
}

// All three bindings are available, and boolReturner() was true.
use(value1, value2, value3)

value1 and value2 are bound exactly as returned. Only value3 is unwrapped, because only that clause is an ordinary guard let unbinding.

The catch and else blocks may be present in any order.

Other forms

The do marker also has a do var variant for mutable bindings, just like the other guard markers. Standard irrefutable pattern matching can be done on the binding side as per let/var rules.

guard do var (a, b) = throwingTupleReturner() catch { ... }

print(a, b)

Not binding any variables is also possible with just do <expr>. The result of the expression, if any, is discarded.

guard do throwingVoidReturner() catch {
    log(error)
    return
}

// un-nested happy path.

This last form is not central to the pitch and can be dropped if it makes the rest harder to justify.

Why guard/do/catch?

guard is the natural spelling for this feature for a few reasons:

  • guard is the idiomatic way to bind conditionally existing variables to the current scope, as seen in guard let for optionals and guard case let for pattern matched values.
  • Swift programmers are used to seeing guard as an indication for early-exit which other spellings don't provide.

The do marker solves quite a few issues present in the other spellings:

  • guard let ... catch {} either does two things at once (error catching and optional unwrapping), or breaks a learned code pattern in a guard let not unwrapping an optional, which was the core team's stated objection to the 2017 pitch.
  • Marking guard statements has precedent in guard case and gives the feature a visually consistent with other language patterns: do signaling error handling and no confusing guard let not unwrapping patterns.

A separate catch block is used for do conditions instead of reusing the standard else block because the blocks are behaviorally equivalent to the catch blocks of a do statement, with pattern matching, implicit error binding, typed throws, and propagation.

This pitch does not aim to replace do/catch as the general mechanism for handling errors. Rather, it addresses a particular use case where guard already offers a useful advantage.

Alternatives considered

do/catch, try?, and Result

Discussed in the Motivation section.

non-guard spellings

As discussed in the "Why guard/do/catch" section, non-guard spellings for this feature aren't idiomatic. Still some of the popular suggestions are discussed below in a bit more detail.

  • do expressions

do expressions, as pitched in Last expression as return value, would let a do/catch produce a value:

let result: Value? = do {
    try thrower()
} catch {
    log(error)
    nil // No early exit
}

// A second condition is needed for early exit.
guard let value = result else { return }

Accepted Swift expression mechanics (see SE-0380 (Accepted)/Control Flow section) restricts control flow out of expressions to thrown errors; they cannot return. The catch branch above therefore cannot exit the scope through a return statement.

The error is collapsed into nil, the else cannot tell a thrown error from an absent value, and non-optional results need an Optional wrapper. This pitch provides the early exit of guard with the error still in hand, so the two features are complementary.

A related suggestion is to relax the branch rules so that a catch can exit, for example let x = do try f() catch { log(error); return }. That would be a larger change to expression semantics, and it would be a different feature from this one: the binding would be unconditional, not a guard condition that composes with others in the same list. And the reasons behind preferring the guard spelling still apply.

  • Braceless do and trailing catch

Several replies proposed making the braces of do optional

do guard let value = try thrower() else { ... } catch { ... }

// Or attach catch directly to an expression.
let value = try thrower() catch { ... }

A braceless do can be read as covering the elsebody, which is the opposite of what this pitch does. In do guard ... else { throw A } catch { ... }, a reader cannot tell whether catch handles A. Here, only do-marked conditions are caught, so errors thrown from an else or catch body always propagate.

A trailing catch on a plain expression would either not have a guaranteed exit condition and thus be the same as do expressions, or it will and clash with the domain of the existing guard feature, which would need some heavy justification.

  • Guard-like do conditions

do let a = try f(), let b = try g() catch { ... } puts the list at statement level instead of inside guard. It cannot be combined with else and does not guarantee an early exit, so the bindings could not be used in the enclosing scope. Again, guaranteeing early exit would fight with the domain of guard statements.

Braced guard do { ... } catch { ... }

A braced form could cover several statements. It would also bring back the nesting and scoping this pitch avoids, and guard do { could be ambiguous with future do expressions.

Un-marked guard conditions

This is by far the most common suggestion in the threads I went through, and one that has been explicitly declined by the core team (see Add a proposal for guard-catch).

The guard try pitch uses no marker: else and catch blocks are attached to an ordinary condition list. A reviewer there asked what the bound type is when the expression is not optional, and the original pitch did not specify it. Without a marker, the type depends on a clause that follows the binding:

func f() throws -> Int? { /* ... */ }

guard let value = try f() else  { return } // propagates; value: Int
guard let value = try f() catch { return } // caught;     value: Int?
guard let value = try f() catch { return } // caught;     value: Int
                          else  { return }

guard let normally promises a non-optional value, so having a trailing clause decide that is easy to misread. The domarker states at the start of the clause that the error is caught and that no unwrapping is implied.

guard try instead of do

guard try can be considered to be in some ways more natural than guard do. This pitch uses do for two reasons:

  • try marks a call site that can throw, while do establishes where errors are caught. do is the keyword that already says "errors stop here".
  • A leading try in a guard condition is legal today and means the opposite: the error propagates.
// The error propagates; the Bool controls execution.
guard try throwingBooleanReturner() else { return }

// The error would be caught; the Bool would be ignored.
guard try throwingBooleanReturner() catch { return }

These two differ only by the trailing keyword, which is easy to misread.

Requiring try inside a do clause

Since a non-throwing expression cannot be marked do, the marker can be read as an implicit leading try. try covers everything to its right, so one marker at the head of the initializer covers the whole expression: try throwing(try throwing()) can be spelled try throwing(throwing()).

guard do let value = a(b(c())) catch { return }

This makes it so that the exact throwing calls aren't marked, but given the right-coverage property of try, that seems suitable, and thus this pitch chooses brevity here. Requiring try would keep every throwing call individually marked, but would put two keywords where one conveys the meaning, which is most visible when nothing is bound:

guard do try throwingVoidReturner() catch { return }

A point against this is that currently swift only allows error propagation from points explicitly marked try/throw, but again see the try's right coverage point. Feedback is encouraged for this point.

Requiring exhaustive catch blocks

An alternative is to require the catch blocks to be exhaustive, so that every error from a do condition is handled where it occurs and never propagates. This would make the exit guarantee come only from the catch blocks, and it would keep propagation from being invisible when try is elided. This pitch does not require it, for these reasons:

  • do/catch does not require it, and following its rules keeps the pitch small.
  • Propagation is guard-compatible. It exits the scope, so the guarantee holds.
  • Requiring a catch-all would force boilerplate in the common case where the caller handles most errors. A function that only wants to special-case FileNotFound would need catch { throw error }.

Given that try is optional as per the current pitch (see “Requiring try inside a do clause”) propagation from a do condition is not marked at the call site, which can be considered non-ideal. Feedback is encouraged for this point.

Order of else and catch

The 2017 gist asked whether an order must be prescribed, and some replies preferred catch before else so that catchvisibly does not cover the else body. Because only do conditions are caught, either order has the same meaning here.

This pitch allows either order since for guard statement with multiple conditions, some do and some case or optional unwrapping, users might want the block order to match the statement order. For a similar reason, the two types of blocks can also be interleved.

guard do let value1 = error1Thrower(),
         let value2 = optionalReturner(),
      do let value3 = error2Thrower()
    catch is Error1 { ... } // 1st condition handler
    else            { ... } // 2nd condition handler
    catch is Error2 { ... } // 3rd condition handler

Feedback is encouraged for this point.

Source compatibility

This change is additive. The do keyword cannot begin a guard condition today, so no existing code changes meaning. The one form not distinguished by a following let or var is guard do <expr>; if do expressions later become legal in conditions, that form's parse would need to be settled alongside them.

ABI stability

No effect on ABI.

4 Likes

This means that the following is completely valid

guard
    do let value = throwingOptionalFunc(),
    let value
catch { ... }
else  { ... }

Do you think this would convey to someone aquatinted with the current system that this means: catch the error from throwingOptionalFunc() while storing its output to value and then unwrap value

While this does solve some issues with determining where error are thrown for the catch block, do is simply an inlined context; the catch block is commonly associated with do as it is a inlined context and as such provides easy encapsulation for catching throwing operations. In short do is tangentially associated with catching Error instance but is not actually indicating that an Error will be thrown, for instance:

do {
    var i = 0
    while i < 5 {
        defer { i += 1 }
        if i % 4 == 3 { i -= 2 }
        print(i)
    }
}

try indicates that an Error can enter the context at that point in execution. Semantically, guard do let would make more sense as a plain binding than a catching binding.

1 Like

At some point, hopefully not too distant in the future, we'll circle back to multi-statement do expressions, which address these shortcomings:

6 Likes

Do expressions are already discussed in the "Alternatives Considered" section. They don't work here (without changing the schematics of how expressions work in Swift currently) because expressions can't return currently in swift and I don't believe the last expression pitch changes that.

Also, none of that changes the fact the guard is the idiomatic way to spell binding a conditionally existing variable with an early-return in swift, so having a guard spelling for error handling would be desirable.

Yes that looks perfectly understandable, especially given the following is valid swift, and means almost exactly what the above one does.

guard
    // resultOptionalThrower returns Result<Value?, any Error>
    case let .success(value) = resultOptionalReturner(),
    let value
else { ... }

// value: Int

That's a valid critique. I still think the use of do here is defendable since a plain binding wouldn't make sense in a guard condition (until do-expressions ship, in which case the braces would disambiguate the two). But assuming further feedback is against it we could change the marker keyword to try (which would make the plain version ambiguous but we could always drop that one since it isn't central to the pitch), or some new third keyword.

All this to say do not being the ideal marker here doesn't change how useful this feature will be, any other suggestions for the keyword is welcome.

I believe there have been a few similar suggestions, which unfortunately didn’t work out, but I’m familiar with this sticking point.

I think the real problem is that, in the else branch of the guard statement, you don’t have access to the thrown error.

I think the cleanest solution is a guard-catch statement.

Having had a look at my code, I think a guard-throw statement would be the better choice, because catch implies that an exception is caught, but I don’t have a case where the method shouldn’t exit after logging.

That is exactly what this proposal pitches though? Only with the addition of a do marker to mark the conditions whose errors are being handled, the guard/catch mechanism remains the same. The 2017 proposal you linked was rejected by the core team with the stated objection being optional unwrapping and error catching being conflated in the same syntax, which this do marker fixes. This has been discussed in the "Alternatives Considered/Un-marked guard conditions" and "Why guard/do/catch" sections.

An exception being caught doesn't mean that the code doesn't exit -- it only means that the automatic throw propagation and stack unwinding is halted and dealt by the programmer explicitly. guard-throw seems to indicate that the catch block always throws, which is not necessarily the case. Escaping the scope can be done through return, break, continue, etc, which the throw spelling doesn't cover, however the guard spelling already does.

1 Like

Thanks for the clarification on the do marker. After reading the pitch more closely, I see that my guard/catch point was already covered.

I like a lot of the ideas here, but I've come to think that the multi-statement then/do expressions pitch from 2023 is the cleaner long-term solution, even though guard has the advantage of combining several conditions in one statement.

The main piece missing there is control flow out of a branch. If return, break and continue were allowed in expression branches, the motivating case would look like this:

for url in urls {
    let data = do {
        try Data(contentsOf: url)
    } catch {
        log(error)
        continue
    }
    process(data)
}

And since it's an expression, the compiler already guarantees that every branch either produces a value, throws, or exits the scope. It also works with async without going through Result:

let config = do {
    try await fetchConfig()
} catch ConfigError.fileNotFound {
    log("Using default config")
    then Config.default
} catch {
    throw AppError.configUnavailable(error)
}

As far as I can tell, SE-0380 left control flow out of expression branches mainly for readability reasons and explicitly kept it open for a future proposal. Since if/switch expressions are restricted to a few positions (initializers, assignments, return values), a return in a branch can't end up hidden in the middle of an argument list, so that concern seems smaller than it first looks.

I think these are two different use cases. guard do … catch is the more "Swifty" option in the sense that it's more convenient to write, especially when several conditions are combined. The expression approach is closer to Rust's match. But I believe the language gains more from fully defined switch/do expressions, because one general mechanism would cover this case and many others, instead of adding a dedicated statement form.

So I'm wondering whether it would make more sense to push the then/do expressions pitch forward first, and then revisit guard do … catch to see what it still adds on top.

1 Like

The last expression as return value pitch already has a lot of contention and is still in its draft stage. A further change to expression behavior allowing branches to exit instead of yielding a value would probably be a similarly debated change. The concept hasn't even been pitched yet, let alone any guarantees for it ever shipping.

The main design philosophy behind this pitch is that it borrows already well established swift patterns (guard statements with early-exit blocks, variables that bind to conditionally existing values, keyword marked non-unwrapping guard conditions) to solve an issue that programmers currently face. Putting it off in anticipation of future language changes which are controversial at best and haven't been pitched yet is not ideal I feel.

As laid out in the pitch body, this change is not in contention with the last expression proposal as currently pitched, there is a clean break between guard do statements signaling an early exit while do expressions signal that the error is consumed and a fallback value is used.

This is true, but it doesn't mean that we need additional control flow tailor-made for that one purpose.

I don’t like the elision of the try keyword, other than that the combination with else may be a bit weird at first but it’s easy to reason about, I could get used to it.

Would very much like to see this (or something like it, anything at this point) come to Swift! I’m a big fan of reducing nesting.

1 Like

The elided try is one of the places I wanted feedback on this pitch. Depending on what the consensus is, I'll change it to be not optional in the formal proposal.

1 Like

FWIW, it's relatively easy to make it more compact with Result, for example:

let result = Result { try thrower() }
guard let value = result.success else {
    log(result.failure)
    return
}
use(value)

Result doesn't have any success or failure computed properties though? You'd need to write your own extension for this to compile.

Even assuming you do that it the error is an optional inside the guard, and if you need a non-optional error for some purpose you need to unwrap it. It also doesn't give you catch's pattern matching. You could write a switch statement but again it is a lot of ceremony for such a common operation.

That's what I meant by relatively easy.

extension Result {
    var success: Success! {
        switch self {
        case .success(let success): success
        case .failure: nil
        }
    }
    var failure: Failure! {
        switch self {
        case .success: nil
        case .failure(let failure): failure
        }
    }
}