Error handling in Swift helps you deal with unexpected issues like network problems, bad input, or file read errors without crashing your app. Swift gives you a clean way to manage these situations using do-try-catch, so you can throw errors when something goes wrong and catch them in one place to handle them properly.
Error Handling Workflow
- Define an Error type (usually an enum conforming to the Error protocol)
- Use throw to raise an error
- Use try to call a throwing function
- Use do-catch to handle the error
Step-by-Step Breakdown of Error Handling in Swift with an Example
Define an Error Type
enum FileError: Error { case fileNotFound case unreadable case encodingFailed
}
Throw an Error in a Function
func readFile(name: String) throws -> String { guard name == "data.txt" else { throw FileError.fileNotFound } return "File content"
}
Handle the Error with do-try-catch
do { let content = try readFile(name: "wrong.txt") print(content)
} catch FileError.fileNotFound { print("⚠️ File not found.")
} catch { print("⚠️ An unknown error occurred: \(error)")
}
Choosing the Right try Approach in Swift
Syntax | Description |
try | Use inside do-catch to handle errors |
try? | Converts the result to an optional, returns nil if error occurs |
try! | Force try — crashes if an error is thrown (only use when you’re sure it won’t fail) |
let result = try? readFile(name: "data.txt") // Optional("File content")
let force = try! readFile(name: "data.txt") // Unsafe if error is thrown
Custom Error Messages
You can conform your error enum to LocalizedError or CustomStringConvertible to provide better messages:
extension FileError: LocalizedError { var errorDescription: String? { switch self { case .fileNotFound: return "The file could not be found." case .unreadable: return "The file is unreadable." case .encodingFailed: return "The file could not be encoded." } }
}
Conclusion
Error handling in Swift lets you manage issues like network errors or bad input without crashing the app. When you hire Swift developers who use do-try-catch well, your app becomes more stable and reliable.