ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Swift Tutorial• 6 min read

Error Handling: do, try, catch & throwing functions

Error protocols, try? optional conversion, and try! forced execution

Error handling in Swift is explicit. Functions capable of failing are marked with throws and invoked with try inside a do...catch block.

The 3 Forms of try in Swift

try: Used inside do { ... } catch { ... } blocks to handle specific failure cases.

try?: Converts the throwing call into an Optional. If the function succeeds, it returns Optional(result); if it throws, it returns nil. Excellent for non-fatal tasks.

try!: Disables error handling and forces execution. Crashes if an error is thrown; use only in unit tests.

Throwing and Catching Custom Errors
enum NetworkError: Error {
    case badURL
    case serverUnavailable
}

func fetchRemoteData(urlString: String) throws -> String {
    guard urlString.hasPrefix("https://") else {
        throw NetworkError.badURL
    }
    return "Encrypted Payload"
}

// 1. Full handling with do-catch
do {
    let data = try fetchRemoteData(urlString: "http://insecure.com")
} catch NetworkError.badURL {
    print("Caught bad URL error!")
} catch {
    print("Other error: \(error)")
}

// 2. Concise try? optional conversion
let safeResult: String? = try? fetchRemoteData(urlString: "https://codexia.org")
try? cleanly converts throwing operations into optionals.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does `try?` do when calling a throwing function in Swift?