How do you implement error handling in Swift using 'throw', 'try', and 'catch'?
Instruction: Explain the process of implementing error handling in Swift and provide an example.
Updated
Official answer
A throwing function marks its signature with throws and throws a value conforming to Error when it cannot satisfy its contract. A caller uses try at the call site and either propagates the error from its own throwing function or handles it in do/catch. A normal try does not handle the error by itself.
This complete local example separates malformed JSON from a decoded value that violates a business rule. It performs no network request:
import Foundation
struct Order: Decodable { let quantity: Int }
enum OrderError: Error { case invalidQuantity }
func decodeOrder(_ data: Data) throws -> Order {
let order = try JSONDecoder().decode(Order.self, from: data)
guard (1...100).contains(order.quantity) else {
throw OrderError.invalidQuantity
}
return order
}
for text in [#"{"quantity":2}"#, #"{"quantity":0}"#, #"{"quantity":"two"}"#] {
do {
let order = try decodeOrder(Data(text.utf8))
print("Accepted quantity: \(order.quantity)")
} catch OrderError.invalidQuantity {
print("Quantity must be from 1 through 100.")
} catch is DecodingError {
print("The order data has an invalid structure.")
} catch {
print("The order could not be read.")
}
}
The outputs distinguish accepted quantity 2, invalid quantity 0 and a type mismatch. Preserve underlying errors when callers need diagnosis; replacing every failure with nil through try? loses that distinction. Use try? only when absence is the intended contract. try! traps if an error occurs and is unsuitable for untrusted input.
Throwing does not roll back earlier side effects or catch arbitrary runtime traps. Validate before committing changes and use a deliberate transaction where needed. For real networking, use asynchronous URLSession APIs and separately handle transport, HTTP status and decoding failures rather than performing synchronous Data(contentsOf:) on the UI path.