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
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)
Login to try C/C++/Java/PHP code in the editor
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
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)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using
try!on a call that could realistically fail; a genuine failure will crash the whole program with no recovery. - Forgetting
try?turns the entire expression into an optional, so a successful call now also needs unwrapping. - 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 intonil.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: