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.
Syntax
let optional = try? throwingFunction() // nil if it throws
let value = try! throwingFunction() // crashes if it throws
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
// Define an enum `ParseError` listing its possible cases
enum ParseError: Error {
// Case `invalidFormat`
case invalidFormat
}
func parseNumber(_ text: String) throws -> Int {
// Unwrap `Int(text)` into `number`, or bail out via the else branch
guard let number = Int(text) else {
throw ParseError.invalidFormat
}
// Return `number` from this function
return number
}
// Declare a constant `good`, set to `try? parseNumber("42")`
let good = try? parseNumber("42")
// Declare a constant `bad`, set to `try? parseNumber("abc")`
let bad = try? parseNumber("abc")
// Print `good as Any` to the console
print(good as Any)
// Print `bad as Any` to the console
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
// Define an enum `ParseError` listing its possible cases
enum ParseError: Error {
// Case `invalidFormat`
case invalidFormat
}
func parseNumber(_ text: String) throws -> Int {
// Unwrap `Int(text)` into `number`, or bail out via the else branch
guard let number = Int(text) else {
throw ParseError.invalidFormat
}
// Return `number` from this function
return number
}
// Declare a constant `number`, set to `try! parseNumber("100")`
let number = try! parseNumber("100")
// Print "Parsed with try!: \(number)" to the console
print("Parsed with try!: \(number)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: