Guard a try block so it only runs when the guard value is set.

← Control Flow · Ref: Q1157

try with guard — body runs only if guard value is set:

  try mainValue <- setValue
    stdout.println(mainValue)
  catch
    -> e as Exception
    stdout.println(e.reason())
  finally
    stdout.println("cleanup")

If setValue is unset, the entire try body is skipped. Finally still runs.

See Q1146 for if-guard. See Q1154 for basic try/catch.

Example

defines module qa.controlflow.tryguardexpression

  defines program

    TryGuardExpressionDemo()
      stdout <- Stdout()

      //Set guard — try body executes
      setValue <- 42
      try mainValue <- setValue
        stdout.println(`Try body: ${mainValue}`)
      catch
        -> e as Exception
        stdout.println(e.reason())
      finally
        stdout.println("Finally: always runs")

      //Unset guard — try body skipped
      unsetValue <- Integer()
      try skipped <- unsetValue
        stdout.println("Should not print")
      catch
        -> e as Exception
        stdout.println("Should not print")
      finally
        stdout.println("Finally on unset guard: still runs")

Common mistakes

E01073 — EK9 has no null literal — 'setValue <- null' is rejected outright; use tri-state semantics (an unset value like Integer()) with the '?' operator instead. See ek9 -h E01073 for details.

Incorrect:

setValue <- null

Correct:

setValue <- 42
Other ways to ask this
  • I need the try body to execute only if a value is present
  • In Swift I'd use 'guard let'. Show the EK9 try guard equivalent
  • Given a possibly-unset value, wrap the try block with a guard assignment
  • Skip the try body entirely when the guard variable is unset

Coming from another language?

Swift: guard let value = optional else { return }. Kotlin: value?.let { }. EK9: try value <- expr — guard on the try itself.

Keywords: try, set, unset, guard, skip, conditional