What is Swift error handling?

Answer

Swift provides a first-class error handling mechanism using the throws, try, catch keywords and the Error protocol. Unlike exceptions in other languages, Swift errors are part of the type system — the compiler ensures you handle them. Defining errors: enum NetworkError: Error { case noConnection case serverError(statusCode: Int) case invalidResponse case unauthorized }. Throwing function: func fetchUser(id: Int) throws -> User { guard isConnected else { throw NetworkError.noConnection } let response = makeRequest(id: id) guard response.statusCode == 200 else { throw NetworkError.serverError(statusCode: response.statusCode) } return parseUser(response.data) }. Handling errors with try/catch: do { let user = try fetchUser(id: 1) print("Found: \(user.name)") } catch NetworkError.noConnection { print("Check your connection") } catch NetworkError.serverError(let code) { print("Server error: \(code)") } catch { print("Unknown error: \(error)") }. try? — convert to optional: let user = try? fetchUser(id: 1) // User? -- nil on error. try! — force, crashes on error: let user = try! fetchUser(id: 1) // Use only if guaranteed to succeed. Propagating errors: func processUser(id: Int) throws { let user = try fetchUser(id: id) // Error propagates up save(user) }. Result type (alternative): func fetch(completion: (Result<User, Error>) -> Void). async throws: func fetchUser(id: Int) async throws -> User { try await networkCall() }.