Error Handling in Swift
Why Error Handling?
Things go wrong: no internet, a missing file, bad input. Swift makes failure visible. A function that can fail is marked with throws, and calling it needs try.
Define Your Own Errors
swift
enum LoginError: Error {
case emptyEmail
case weakPassword(minLength: Int)
case wrongCredentials
}
func login(email: String, password: String) throws -> String {
guard !email.isEmpty else { throw LoginError.emptyEmail }
guard password.count >= 6 else { throw LoginError.weakPassword(minLength: 6) }
guard password == "secret1" else { throw LoginError.wrongCredentials }
return "token-123"
}
Catching Errors
swift
do {
let token = try login(email: "a@b.com", password: "abc")
print("Logged in with \(token)")
} catch LoginError.emptyEmail {
print("Please enter your email")
} catch LoginError.weakPassword(let minLength) {
print("Password needs at least \(minLength) characters")
} catch {
print("Other error: \(error)")
}
try? and try!
swift
let token = try? login(email: "a@b.com", password: "secret1") // String? : nil on error
let sure = try! login(email: "a@b.com", password: "secret1") // crashes on error, avoid
Friendly Messages: LocalizedError
swift
extension LoginError: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyEmail: return "Please enter your email."
case .weakPassword(let n): return "Use at least \(n) characters."
case .wrongCredentials: return "Email or password is wrong."
}
}
}
// In a view model
do {
_ = try login(email: email, password: password)
} catch {
errorMessage = error.localizedDescription
}
defer: Always Clean Up
swift
func readFile() throws {
let handle = try openFile()
defer { closeFile(handle) } // runs when the function exits, even on error
try process(handle)
}
Result Type
swift
func parse(_ text: String) -> Result<Int, Error> {
if let n = Int(text) { return .success(n) }
return .failure(LoginError.wrongCredentials)
}
switch parse("42") {
case .success(let n): print(n)
case .failure(let error): print(error)
}
Modern style: With async/await, most code uses
throws and do-catch. Result is mainly useful for older callback-based APIs.
Conclusion
Error handling makes problems explicit. Use throws and do-catch, show friendly messages, and avoid try!.
Quick Summary: Mark failing functions with throws, call them with try inside do-catch and avoid try!.

