Skip to content
DeveloperMemos

How to Catch a Specific Type of Error in Swift

Swift, Error Handling1 min read

Error handling is a mechanism in Swift that allows you to handle errors that occur during the execution of your code. In Swift, you can represent errors as values of types that conform to the Error protocol. When an error occurs, you can throw an error value from a function, method, or initializer, and catch it using one or more catch statements.

The do-catch Statement

The do-catch statement is used to handle errors in Swift. It consists of two parts: the do block and the catch block. The do block contains the code that may potentially throw an error. The catch block contains the code that handles the error if it occurs.

Here's an example:

1do {
2 // Code that may throw an error
3} catch {
4 // Code that handles the error
5}

In the catch block, you can access the error using the error parameter. You can then handle the error by printing out a message, logging it, or taking some other action.

Catching a Specific Type of Error

Sometimes, you may want to catch a specific type of error, rather than any error that is thrown. For example, you may have a function that throws multiple types of errors, and you want to handle each type differently.

To catch a specific type of error, you can add a type annotation to the catch statement. Here's an example:

1do {
2 // Code that may throw an error
3} catch let error as MyCustomErrorType {
4 // Code that handles MyCustomErrorType
5} catch let error as AnotherCustomErrorType {
6 // Code that handles AnotherCustomErrorType
7} catch {
8 // Code that handles any other error
9}

In this example, we're catching two custom error types, MyCustomErrorType and AnotherCustomErrorType, and handling them separately. Any other error that is thrown will be caught by the last catch block.

Note that the order of the catch blocks matters. If you put the catch block for a more general type before the catch block for a more specific type, the more general catch block will catch the error first, and the more specific catch block will never be executed.

Conclusion

Catching a specific type of error in Swift is easy with the catch statement and do-catch block. By adding a type annotation to the catch statement, you can catch only the errors of a specific type and handle them accordingly. This makes your error handling more precise and helps you provide better feedback to your users.