Avoid Dangerous Try

ID

swift.avoid_dangerous_try

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Swift

Tags

error-handling, reliability

Description

Reports use of the try! operator. The forced variant skips error handling and crashes the process with an unhandled error if the call throws — the same failure mode as force-unwrapping a nil Optional.

let photo = try! loadImage(atPath: "...")   // FLAW

let photo = try? loadImage(atPath: "...")   // OK — returns Optional
do {
    let photo = try loadImage(atPath: "...")
} catch {
    // handle error
}                                            // OK

Rationale

try! violates Swift’s structured error-handling model. The thrown error is never inspected; the program just terminates. In production code this turns a recoverable I/O / parsing failure into a hard crash visible to the end user.

Acceptable narrow exceptions:

  • Test code, where the failure mode is "test fails noisily".

  • Invariants proven at compile time (rare in practice).

Remediation

// Option 1: try? — returns Optional, no throw.
let photo = try? loadImage(atPath: path)
guard let photo = photo else {
    return // or fallback
}

// Option 2: do / catch — full error handling.
do {
    let photo = try loadImage(atPath: path)
    // use photo
} catch {
    // log / recover / surface to user
}