SyntaxStudy
Sign Up
Swift Error Handling with do-catch
Swift Beginner 1 min read

Error Handling with do-catch

Swift has a structured error handling system using throw, try, do-catch, and rethrows. Functions that can fail are marked throws and called with try. Errors are types conforming to the Error protocol. Custom error enums with associated values provide rich error information. The try? operator converts a throwing expression to an optional (nil on error), and try! forces success (crashes on error). Use these sparingly.
Example
import Foundation

enum ParseError: Error {
    case invalidInput(String)
    case outOfRange(value: Int, min: Int, max: Int)
}

func parseAge(_ input: String) throws -> Int {
    guard let age = Int(input) else {
        throw ParseError.invalidInput("'\(input)' is not a number")
    }
    guard (0...150).contains(age) else {
        throw ParseError.outOfRange(value: age, min: 0, max: 150)
    }
    return age
}

// do-catch
do {
    let age = try parseAge("25")
    print("Age: \(age)")
} catch ParseError.invalidInput(let msg) {
    print("Invalid: \(msg)")
} catch ParseError.outOfRange(let val, let min, let max) {
    print("\(val) must be between \(min) and \(max)")
} catch {
    print("Unexpected error: \(error)")
}

// try? - returns optional
let age1 = try? parseAge("abc")  // nil
let age2 = try? parseAge("30")   // Optional(30)

// Propagating errors
func validateUser(name: String, ageStr: String) throws -> String {
    let age = try parseAge(ageStr)
    return "\(name) is \(age) years old"
}