How do you handle errors in Swift?

Instruction: Describe the process of error handling in Swift, including the use of 'throw', 'try', and 'catch' keywords.

Context: This question assesses the candidate's knowledge of Swift's error handling model, which is crucial for building robust applications that can gracefully handle failures and unexpected conditions.

Updated

Official answer

A throwing Swift function declares throws and uses throw to report a recoverable error. Call it with try. A caller can catch the error in do/catch or propagate it from another throwing function; it does not have to catch it at every call site.

enum CountError: Error {
    case malformed
    case nonpositive
}
func readCount(_ text: String) throws -> Int {
    guard let value = Int(text) else { throw CountError.malformed }
    guard value > 0 else { throw CountError.nonpositive }
    return value
}

do {
    let count = try readCount("3")
    assert(count == 3)
} catch {
    assertionFailure("Unexpected error: \(error)")
}
do {
    _ = try readCount("0")
    assertionFailure("Expected a failure")
} catch CountError.nonpositive {
    print("Enter a positive count")
} catch {
    print("Could not parse the count")
}
let maybe = try? readCount("invalid")
assert(maybe == nil)

try? converts failure to nil and discards which error occurred, so use it only when that loss is intentional. try! traps if an error is thrown and is unsuitable for ordinary user input or network failures. A defer block can release a resource when its scope exits, including during error propagation; a thrown error does not automatically roll back external side effects.

At the feature boundary, map known errors to useful recovery such as editing input, retrying a safely repeatable request or signing in again. Preserve diagnostic context without exposing secrets. Cancellation should normally remain cancellation rather than being reported as a successful empty result. Test both the error classification and the state left after failure.

Swift error handling

Related Questions