skip to content

In Swift, what do try? and try! do with a thrown error, and when does try? hide a bug?

level: middleimportance: must knowfreq 72%

answer

  1. one gives nil, one crashes
  2. the error value is discarded
  3. flattening since Swift 5
  4. statement form on a Void call

basics

~20 s

try? turns a thrown error into nil and discards it, so the result is optional; try! traps at run time, even in -O builds. try? hides a bug when the failure needed logging, showing, or telling apart from a real nil.

solid answer

~40 s

`try?` evaluates the call and yields its value wrapped in an optional, or `nil` if it threw; the error itself is thrown away. Since Swift 5 it flattens, so `try?` on a `String?`-returning call is `String?`, not `String??`. `try!` yields the plain value and stops the program with "'try!' expression unexpectedly raised an error" if the call throws, and that check survives `-O`. `try?` hides bugs when a statement like `try? save(rows)` silently drops a failed save, when a flattened `nil` could mean either "no result" or "it failed", or when a user-facing import shows nothing instead of the row that broke. Use `try?` only where every failure honestly means "no value", and `try!` only where failure would be a programming error.

code

swift · 19 lines
swift
enum ReadError: Error { case fileNotFound(String) }
enum ValidationError: Error { case badEmail(line: Int) }

func loadText(at path: String) throws -> String {
    throw ReadError.fileNotFound(path)
}
func firstEmail(in text: String) throws -> String? { nil }
func save(_ rows: [String]) throws { throw ValidationError.badEmail(line: 4) }

let text = try? loadText(at: "contacts.csv")   // String?, and the ReadError is gone
print(type(of: text), text as Any)             // Optional<String> nil

let email = try? firstEmail(in: "")            // String?, flattened since Swift 5
print(type(of: email))                         // Optional<String>

try? save(["ada"])                             // no warning: the failed save vanishes

let header = try! loadText(at: "contacts.csv") // traps here
print(header)

go deeper

for a junior

Recall the two behaviours: try? gives nil when the call throws, try! crashes, and both still need a throwing call after them.

for a middle

Explain flattening, the optional result type, the trap message of try!, and why a statement-form try? on a Void call compiles without a warning.

for a senior

Show how you review call sites: which try? hides a failure the user or the logs should see, and which try! depends on input the code does not control.

for a principal

Argue where swallowing failures is acceptable, such as best-effort caches, and where a team should insist on do-catch so failures stay diagnosable.

## try? turns an error into nil `try?` is an **optional-try** expression. If the expression after it returns normally, the result is that value wrapped in an optional; if it throws, the result is `nil`. The book shows that `let x = try? f()` behaves exactly like a `do`-`catch` that assigns `nil` in a bare `catch`. Two consequences follow: - The **error value is discarded**. Nothing is logged, and the caller cannot tell a missing file from a malformed one. - The result type is **optional**. Since Swift 5 (SE-0230) `try?` **flattens**: on a function that already returns `String?`, `try?` gives `String?`, not `String??`. Before Swift 5 it produced a double optional. `try?` reads well in a chain of fallbacks, the book's own example being `if let data = try? fetchDataFromDisk() { return data }` followed by a server fetch. ## try! asserts that no error happens `try!` is a **forced-try** expression. Its value is the expression's value, not an optional. If the expression throws, the program stops with a runtime error; Swift 6.4 prints "Fatal error: 'try!' expression unexpectedly raised an error:" followed by the error. This check is still present in an optimized `-O` build, so `try!` is not a debug-only assertion. The book's legitimate use is a call that cannot fail in practice, for example loading an image resource that ships inside the app bundle. Anything that depends on the network, the user's file system or user input does not qualify. ## When try? hides a bug `try?` is a decision to treat every failure the same way and forget why it happened. That becomes a bug in a few recognisable places: 1. **Void-returning calls.** `try? exporter.save(rows)` as a statement compiles with no warning, so a failed save leaves no trace. Assigning it, as in `let saved = try? save(rows)`, only earns the warning "constant 'saved' inferred to have type '()?', which may be unexpected". 2. **Functions that already return an optional.** With flattening, `try? firstEmail(in: text)` is `nil` both when the row has no email and when parsing threw. The two meanings collapse into one. 3. **Errors someone should see.** Wrapping a CSV import step in `try?` turns "row 12 has an unterminated quote" into an empty result, and the user sees a file that "imported nothing". 4. **Tests.** A test that calls the code under test with `try?` passes when the code throws, which is the opposite of what it was written to check. The fix is to keep `try?` for failures you would genuinely handle by ignoring them, and to use `do`-`catch` wherever the error should be logged, shown or mapped. A short `do`-`catch` that logs the error and then returns `nil` keeps the optional result without losing the diagnosis. ## Choosing among the three forms | Form | Result type | On error | Use when | |---|---|---|---| | `try` | the value | propagates to a `catch` or the caller | the error matters to someone | | `try?` | optional, flattened | becomes `nil`, error discarded | every failure means "no value" and nobody needs the reason | | `try!` | the value | runtime trap, also in `-O` builds | the call cannot fail unless the program itself is wrong | Choosing between returning an optional and throwing as an API design question belongs with the material on `Result` and failure strategy; this answer is about the call site. ## Reviewing try? and try! in a pull request A short checklist catches most of the problems above: - Is the `try?` result used? A discarded result makes the failure invisible, so ask whether anyone would want to know about it. - Does the called function already return an optional? Then `nil` carries two meanings after flattening. - Is the `try!` input under the program's control, such as a literal, a bundled resource or a value validated a line earlier? If it comes from a file, the network or the user, it is a crash waiting for bad data. - Would a `do`-`catch` with a log line cost more than a few extra lines? Usually it would not. ## A worked line-by-line reading In the snippet, `loadText` always throws, so `text` is `nil` and its static type is `Optional<String>`. `firstEmail` returns `String?`, and `try?` keeps it a single optional. The statement `try? save(["ada"])` swallows a `ValidationError` without a diagnostic. Finally `try! loadText(...)` traps, so the last `print` never runs.

  • What type does try? give for a function declared throws -> String?, and has that always been so?
    `String?`. Since Swift 5 (SE-0230) `try?` flattens its result instead of adding another optional layer, so a thrown error and a returned `nil` both end up as the same `nil`. Before Swift 5 the expression was `String??`, which kept the two apart at the cost of awkward unwrapping.
  • Does try! still check for errors in an optimized -O build?
    Yes. Building with `-O` and calling `try!` on a function that throws still stops with "Fatal error: 'try!' expression unexpectedly raised an error". Unlike `assert`, it is not compiled out, so it is a crash in production, not just in debug runs.
  • How do you keep an optional result but still record why a call failed?
    Replace `try?` with a small `do`-`catch` that logs or reports the error in the `catch` and then returns `nil`. Callers still get an optional, but the reason for the failure reaches your logs instead of disappearing.

  • try? logs the error before it returns nil.
  • try! is stripped from release builds, like assert.
  • try? on a function returning String? gives String?? in Swift 5 and later.
  • Swift warns whenever a try? result is unused, so nothing is silently lost.
  • try! is fine wherever the call usually succeeds.