Error Handling Example in Swift

In this tutorial, you will learn how to handle errors in Swift.

Errors in Swift are unexpected events that occur during program execution. They can be caused by various factors such as invalid user input, device failure, loss of network connection, physical limitations (like running out of disk memory), or code errors.

Throw Statement

In Swift, you can indicate that a function or method can throw an error using the throw statement. This informs the caller that they should handle potential errors.

Notice in the code example below, the fetchData() function has the throws statement right after the function name.

enum NetworkError: Error {
   case noInternet
   case serverError
}

func fetchData() throws {
   ...
   if !isConnectedToInternet {
       throw NetworkError.noInternet
   }

   // Fetch data from the server
}

In the above code example, I created a NetworkError enum with cases for handling connectivity issues (noInternet and serverError). If there’s no internet connection, the function fetchData() throws an NetworkError.noInternet error.

Handle Errors with Do-Catch Statement

The do-catch statement allows you to catch and handle errors in a structured manner. It provides a safe way to handle errors and offers flexibility in error recovery.

Here’s how it works:

do {
   try fetchData()
   // Data fetched successfully
} catch NetworkError.noInternet {
   // Handle the no internet error
   print("No internet connection.")
} catch NetworkError.serverError {
   // Handle the server error
   print("Server error occurred.")
} catch {
   // Handle other errors
   print("An unexpected error occurred.")
}

In this example, if fetchData() throws an error, it gets caught in the corresponding catch block. For a serverError, it prints “Server error occurred.” Otherwise, it catches and prints “An unexpected error occurred.” This concise approach offers targeted error responses during data fetching.

Handling Specific Types of Errors with Do-Catch

Sometimes, you might want to handle specific types of errors separately. You can achieve this by creating specific catch blocks for each error type.

do {
   try update(name: "ferdous", forUserIdentifier: "123")
} catch User.ValidationError.emptyName {
   // Handle empty name error
} catch User.ValidationError.nameToShort {
   // Handle short name error
} catch {
   // Handle all other errors
}

In this example, different types of validation errors are caught and handled separately.

You create a do-catch block to update a user’s name.

  • If the name is empty, it handles the empty name error;
  • If it’s too short, it handles the short name error.
  • Any other errors are caught and handled generically.

Conclusion

I hope this tutorial was helpful to you.

For more Swift Code examples and tutorials, please check the Swift Code Examples page on this website.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *