Handling errors with do-catch in Swift
Errors are a normal part of iOS development. A network request can fail, a user can enter an invalid value, or a JSON response can change without warning. Swift’s error-handling system gives you a clear way to detect these situations and decide what the app should do next.
The do-catch statement is central to that system. It lets throwing functions report failure without forcing every function to return an optional or a custom status flag. For junior developers building UIKit or SwiftUI apps, learning to use it well makes code easier to read, test and maintain.
| Approach | Best used for | What it communicates |
|---|---|---|
do-catch |
Handling a throwing operation immediately | The app can respond to specific failures |
try? |
Ignoring or simplifying a failure | The result may be unavailable |
try! |
A condition that is guaranteed by design | Failure should be treated as a programming bug |
Result |
Passing success or failure through a callback or property | An operation has one of two explicit outcomes |
throws |
Letting a lower-level function report failure | The caller is responsible for recovery |
What Swift errors represent
Swift errors describe recoverable problems rather than crashes. Any type that conforms to the Error protocol can represent a failure, from a built-in decoding issue to a custom validation case. A throwing function adds throws to its declaration, while the caller uses try to acknowledge that the operation may fail.
For example, a sign-up screen might throw an error when an email address is malformed or a password is too short. A weather app used in Melbourne could fail because the device is offline, while an app used in regional Western Australia might need to handle a slow or intermittent connection. These are expected runtime conditions, so they should be handled deliberately.
A thrown error does not automatically show an alert or fix the problem. It travels up the call stack until a suitable do-catch block handles it. This separation keeps networking, validation and user-interface code from becoming tightly tangled.
How do-catch controls throwing code
A do block contains code that may throw. If an error occurs, Swift skips the remaining statements in that block and searches the associated catch clauses. Each clause can match a particular error, and a final general catch can handle anything that has not been matched.
enum LoginError: Error {
case emptyEmail
case invalidPassword
case serverUnavailable
}
func login(email: String, password: String) throws {
guard !email.isEmpty else { throw LoginError.emptyEmail }
guard password.count >= eight else { throw LoginError.invalidPassword }
}
The number in that example should be written as 8, so a complete call would look like this:
do {
try login(email: email, password: password)
showHomeScreen()
} catch LoginError.emptyEmail {
showMessage("Enter your email address.")
} catch LoginError.invalidPassword {
showMessage("Use at least eight characters.")
} catch {
showMessage("Something went wrong. Please try again.")
}
The order matters. Specific cases should come before the broad catch, because the general clause can match every error. You can also inspect the error with error, or use pattern matching when an error carries associated data. This gives the interface enough information to show a useful message rather than a vague “failed” label.
Use try? when failure genuinely means “no value”. For instance, let savedName = try? loadName() may be suitable for an optional preference. Avoid try! in ordinary app logic: a failed force-try causes a crash and is especially risky in an App Store release.
Create useful custom errors
Custom error types make the intent of your code visible. An enum is usually a good starting point because its cases describe the failure categories directly.
enum ProfileError: LocalizedError {
case missingName
case invalidAge
case duplicateUsername
var errorDescription: String? {
switch self {
case .missingName:
return "Please enter your name."
case .invalidAge:
return "Enter an age between 13 and 120."
case .duplicateUsername:
return "That username is already taken."
}
}
}
LocalizedError is useful when an error needs a user-facing description. It still helps to keep presentation decisions in the view controller or view model. The error should describe what happened; the UI should decide whether that means an alert, an inline label or a retry button.
Associated values can preserve useful context. An error such as case httpStatus(Int) tells you whether a server returned 401, 404 or 500. Do not expose technical details blindly, though. A raw database message may help a developer but confuse a user. For Australian users, clear wording such as “You appear to be offline” is more helpful than displaying a URLSession error code.
Keep async and networking failures readable
Modern Swift uses async throws for asynchronous work that can fail. A networking service can focus on fetching and decoding data, then allow the calling layer to decide how to respond.
struct Forecast: Decodable {
let temperature: Double
}
func fetchForecast() async throws -> Forecast {
let url = URL(string: "https://example.com/forecast")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode else {
throw URLError(.badServerResponse)
}
return try JSONDecoder().decode(Forecast.self, from: data)
}
A view model can then catch failures on the main actor and update state safely:
do {
forecast = try await service.fetchForecast()
} catch is DecodingError {
message = "The forecast data could not be read."
} catch {
message = "Check your connection and try again."
}
Separate transport, server and decoding errors where that distinction changes the user experience. A timeout may deserve a retry button, while invalid JSON should be logged and reported for investigation. Testing these paths is important when your app targets users across Australia, from fast Sydney connections to areas where mobile coverage can be less reliable.
The same principle applies when an app reads untrusted external content. If a prototype parses an article such as this 10-dollar pokies deposit guide, malformed markup, unavailable content or unexpected fields should produce a controlled error rather than a crash. Treat every remote response as data that needs validation, regardless of how simple the source appears.
Practices that make error handling stronger
Good error handling is a design habit rather than a final layer added after the feature is complete. Decide which failures belong in the service, which should reach the view model and which deserve user-visible feedback.
For a junior developer building a portfolio project or preparing a Swift Student Challenge submission, these practices keep the implementation focused:
- Define custom error cases around actions users understand, such as validation, authentication or unavailable data.
- Match specific errors before using a general
catchclause. - Give users plain-language messages and keep debugging details in logs.
- Use
try?only when losing the error is acceptable and expected. - Avoid
try!for network requests, user input and other runtime conditions. - Add retry, empty-state or offline behaviour where the failure can be recovered.
- Test both successful operations and every important failure case.
A useful rule is to handle an error at the lowest level that has enough information to make a sensible decision. A networking layer can identify a bad HTTP status, but a view model may be the first layer that knows whether to show an alert or an empty state. Keeping that boundary clear prevents duplicated messages and confusing control flow.
Test the failure paths deliberately
Error handling is incomplete until the failure paths have been tested. With XCTest, create tests for invalid input, thrown custom errors, decoding failures and server responses outside the successful 2xx range. A function that works perfectly with valid JSON may still fail when a field is missing or has the wrong type.
You can inject a mock service into a view model instead of calling a real server. The mock can return a successful forecast, throw a timeout, or provide invalid data. This makes tests fast and repeatable, and it avoids relying on internet access or a live backend.
During development, log technical context without exposing private information. OSLog can record a request failure, status code and affected feature while the interface shows a concise message. Avoid logging passwords, authentication tokens or complete personal records, particularly when testing with real devices.
The main idea to remember is simple: do-catch gives Swift code a structured path for failure. Define meaningful errors, catch them at the right layer, communicate them clearly and test them as carefully as the successful path.