Handling Errors and Exceptions in Swift
Q: How would you handle errors and exceptions in Swift? Can you provide a code example?
- IOS
- Junior level question
Explore all the latest IOS interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create IOS interview for FREE!
In Swift, errors and exceptions are handled using the `try`, `catch`, and `throw` keywords.
Here's an example of how you might handle errors in Swift:
enum NetworkError: Error { case invalidURL case serverError(statusCode: Int) case invalidResponse } func fetchData(from urlString: String) throws -> Data { guard let url = URL(string: urlString) else { throw NetworkError.invalidURL } let request = URLRequest(url: url) let (data, response, error) = URLSession.shared.syncDataTask(with: request) guard let httpResponse = response as? HTTPURLResponse else { throw NetworkError.invalidResponse } guard (200...299).contains(httpResponse.statusCode) else { throw NetworkError.serverError(statusCode: httpResponse.statusCode) } if let error = error { throw error } return data } do { let data = try fetchData(from: "https://example.com/data") // Do something with the data } catch NetworkError.invalidURL { print("Invalid URL provided") } catch NetworkError.serverError(let statusCode) { print("Server error with status code \(statusCode)") } catch NetworkError.invalidResponse { print("Invalid response received") } catch { print("An unknown error occurred: \(error)") }
In this example, we define a custom `NetworkError` enum to represent possible errors that might occur while fetching data from a network resource. The `fetchData(from:)` function takes a URL string as input and uses it to fetch data from the specified resource. If an error occurs at any point during the process (e.g. an invalid URL is provided, a server error occurs, etc.), the function throws the corresponding `NetworkError` or other error.
To handle the errors thrown by `fetchData(from:)`, we use a `do-catch` block. The code inside the `do` block attempts to fetch data from the network resource using `fetchData(from:)`. If an error is thrown, the `catch` blocks are executed in order until a matching block is found. If no matching block is found, the `catch` block at the end of the list is executed, which handles all other types of errors.
Overall, handling errors in Swift involves defining custom error types, throwing and catching errors using the `try-catch` syntax, and handling errors in an appropriate way for your app's needs.


