Swift uses throws and catch for error handling.
Defining Errors
SWIFT
enum NetworkError: Error {
case invalidURL
case timeout
case serverError(code: Int)
}Throwing and Catching
SWIFT
func fetchUser(id: Int) throws -> String {
guard id > 0 else { throw NetworkError.invalidURL }
return "User \(id)"
}
do {
let user = try fetchUser(id: 1)
print(user)
} catch NetworkError.invalidURL {
print("Invalid URL")
} catch {
print("Unexpected error: \(error)")
}try? and try!
SWIFT
let user = try? fetchUser(id: 999) // returns nil on error
let sureUser = try! fetchUser(id: 1) // crashes on errorTips
- Use
try?when failure is expected and you want a graceful nil. - Use
try!only when failure is truly impossible. - Define specific error cases with associated values for rich information.
Next: collections.