← Back to Swift Course | Chapter 11: Error Handling | Lesson 4 of 6

try? and try!

try? quietly turns a possible failure into nil instead of crashing, while try! bets everything that it will succeed, crashing hard if it doesn't.

Using try? to Get an Optional

try? converts a throwing function's result into an optional: a real value on success, or nil if it throws.

Example: Using try? to Get an Optional

markup
enum ParseError: Error {
    case invalidFormat
}
func parseNumber(_ text: String) throws -> Int {
    guard let number = Int(text) else {
        throw ParseError.invalidFormat
    }
    return number
}
let good = try? parseNumber("42")
let bad = try? parseNumber("abc")
print(good as Any)
print(bad as Any)

Using try! When Failure Is Impossible

try! should only be used when you are absolutely certain the call cannot fail, since any thrown error becomes an immediate crash.

Note: If the string here were not a valid number, try! would crash the program immediately -- use it sparingly.

Example: Using try! When Failure Is Impossible

markup
enum ParseError: Error {
    case invalidFormat
}
func parseNumber(_ text: String) throws -> Int {
    guard let number = Int(text) else {
        throw ParseError.invalidFormat
    }
    return number
}
let number = try! parseNumber("100")
print("Parsed with try!: \(number)")
Common Mistakes
  1. Using try! on a call that could realistically fail; a genuine failure will crash the whole program with no recovery.
  2. Forgetting try? turns the entire expression into an optional, so a successful call now also needs unwrapping.
  3. Overusing try? to silently swallow errors that should actually be inspected and handled, losing valuable failure information.
Chapter Summary
  • try? converts a throwing call's result into an optional, turning any error into nil.
  • try! force-runs a throwing call, crashing the program if it actually throws.
  • try? is useful when you only care whether something succeeded, not why it failed.
  • try! should be reserved for cases where failure is truly impossible or a genuine programming error.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.