Error Basics in Swift

From the Swift cheat sheet · Error Handling · verified Jul 2026

Error Basics

Defining and throwing errors

swift
// Error definition
enum FileError: Error {
    case notFound
    case permissionDenied
    case corrupted(reason: String)
}

// Throwing function
func readFile(named name: String) throws -> String {
    guard fileExists(name) else {
        throw FileError.notFound
    }
    return "File contents"
}

// Do-catch
do {
    let contents = try readFile(named: "data.txt")
    print(contents)
} catch FileError.notFound {
    print("File not found")
} catch {
    print("Unexpected error: \(error)")
}

// Try? and try!
let contents = try? readFile(named: "data.txt")  // Returns optional
💡 Errors must conform to Error protocol
⚡ try? converts throwing results to optionals
📌 defer executes code when scope exits
🟢 Use specific error cases for clear error handling
Back to the full Swift cheat sheet