Swift error handling — with examples

Error handling in Swift is a mechanism for dealing with errors or exceptional situations that may occur in your code. It allows you to identify and respond to potential problems in a controlled and predictable manner, rather than allowing them to cause your program to crash.

In Swift, errors are represented by values of types that conform to the Error protocol. When a function encounters an error, it can throw an error using the throw statement. The error can then be caught and handled by a surrounding do-catch statement.

Swift Do-catch

In the short guide/tutorial we will learn how to error handling in swift with an simple example.

When you are developing an iOS app and your code encounters an error, it cannot handle it will simply crash the app and the user will have to start over — no one wants that.

The do-catch statement in Swift is used to handle errors in your code. The do block contains code that may throw an error, and the catch block contains code that should be executed if an error is thrown.

Typically when you get data from an API and are parsing from JSON to a Swift object, you want to use do-catch. In the following example we will create a function that parses from JSON to an object:

func getData(dataToParse: Data) {
            do {
                let parsedToObject = try JSONDecoder().decode(SomeObject.self, from: dataToParse)
                success(profiles)
            }catch {
                print("Error")
            }
        }
    }

As you can see the syntax is straightforward:

do {
   //Code that might fail example parse json to object
}catch{
  //The error is catched and the app can continue
}

Now that is a great example of where you always want to create a do-catch.

But sometimes you are creating a function that might fail and therefore you want to throw an error.

Swift throw error — error handling with enum

In Swift, you can use enums to define custom error types and make error handling more structured and expressive. An enum can be used to define a set of error cases that a function can throw.

Let’s say you are creating a function and want to throw an error, you can do that in 3 easy steps — create an Error enum, create a function that throws, and a function that catches.

We will define a custom error for network requests.

1. Create a custom error that conforms to Error

The first thing we need to do is define our NetworkError enum:

enum NetworkError: Error {
    case serverError(errorCode: Int)
    case invalidURL(url: String)
}

serverError: indicates that the server returned an error, and includes the error code returned by the server.

2. Function the throws error

Now we need to use our NetworkError and we will pretend to create an API request.

func executeRequest(url: String) throws -> Data {
    guard let url = URL(string: url) else {
        throw NetworkError.invalidURL(url: url)
    }

    let response = try getResponse(from: url)

    if response.errorCode < 200 && response > 299 {
        throw NetworkError.serverError(errorCode: response.errorCode)
    }

    return response
}

The code above will throw a NetworkError.invalidURL if the URL passed to the function does not conform to a URL and a NetworkError.serverError if the response status code isn’t successful — below 200 and above 299.

3. Function that catches the NetworkError

Now it’s time to make a function that uses executeRequest and catches the errors:

do {
    let data = try executeRequest()
    // handle the received data
} catch let error as NetworkError {
    // handle the specific NetworkError cases
    switch error {
    case .invalidURL(let invalidUrl):
        print("Not a valid URL: \(invalidUrl)")
    case .serverError(let errorCode):
        print("Server said no: \(errorCode)")
    }
} catch {
    print("Any other error: \(error)")
}

Conclusion

In conclusion, error handling is a critical practice in Swift programming that can improve the quality and reliability of code. 

By handling errors effectively, developers can prevent unexpected and potentially catastrophic crashes or bugs that may negatively impact the user experience. 

The use of error handling in Swift can help to detect and respond to errors in a more controlled and predictable manner, allowing for more robust code and better application stability.

Additionally, by incorporating error handling in Swift, developers can provide better feedback to users, allowing them to understand what went wrong and take corrective action. This can improve the overall user experience and reduce the number of support requests or negative reviews.

What is error handling in Swift?

Error handling is a mechanism in Swift that allows you to handle unexpected or undesirable situations in your code, such as network errors, file I/O errors, or missing data. Error handling helps you write robust and reliable code by allowing you to anticipate and respond to errors.

In Swift, error handling is based on the concept of throwing and catching errors. When a function encounters an error, it throws an error and the caller of the function can catch the error and respond appropriately.

How do you throw an error in Swift?

You can throw an error in Swift by using the throw statement. The throw statement is used to indicate that an error has occurred and to propagate the error to the caller of the function.

See above example: Swift throw error — error handling with enum for greater detail.

Scroll to Top