Error Handling in Swift

Updated 29 July 2021


Error handling is the process of responding to and recovering from error conditions in your program. In many situations, we may have to deal with errors. Sometimes we also have to let the co-workers know that the program throws the error. I will try to explain every aspect of error handling here in this article.

Some operations cannot guaranteed to always complete execution or produce a useful output. The optional can be used to represent the absence of a value, but when an operation fails.

As an example, consider the task of reading and processing data from a file on disk. There number of ways this task can fail, including the file not existing at the specified path, the file not having read permissions, or the file not being encoded in a compatible format. Distinguishing among these different situations allows a program to resolve some errors and to communicate to the user any errors it can’t resolve.

Swift Error Handling used for handling the failing conditions gracefully. An error can lead to runtime errors or changes in the flow of the program. We come across different kinds of errors in our projects:

The brute force way to handle errors is by using if else statements where we check each and every possible error. But this can lead to bloated codes with too many nested conditions.

In Swift, Errors are just values of a certain type. Swift does not support checked exceptions.’

Swift Error Protocol

Error Protocol is just a type for representing error values that can be thrown. Swift requires you to create a custom Error type. Typically an Enum is used which conforms to the Error protocol. It is more or less empty. Hence you don’t need to override anything from them. It is a must for Error Handling and creating Error types.

Let’s create a basic enum which conforms to this Error Protocol.

Now let’s use this Error Type in our classes and functions.

throws and throw

If a function or an initializer can throw an error, the throws modifier must be added in the definition itself right after the paratheses and just before the return type.

The throws keyword would propagate the error from the function to the calling code.
Otherwise, a non-throwing function must handle the error inside that function’s code itself.

throw keyword is used for throwing errors from the error type defined.

Let’s look at an example demonstrating throws and throw in a function:

In Error Handling, guard let is useful in the sense that we can replace the return statement in the else block with the throwing error. This prevents too many if-else conditions.
Let’s look at it with the example below.

Note: You cannot add the Error type after the throws keyword in Swift.

In the above code, if the condition in the guard let fails it’ll throw an error and the function would return there itself.
Let’s look at how to handle these errors.

Swift try, do-catch

In Swift, contrary to Java, do-catch block is used to handle errors in place of try-catch.

Every function that has throws needs to set in the try statement since it has a potential error.

Swift try statement is executed only when it is inside the do-catch block as shown below.

The below image shows the output of the above program.

swift error handling, swoft try catch example

Alternatively, we can do this:

Throwing Errors in Initializers

We can add throws in the initializer in the following way.

Now to initialize the class:

Since the initializer is throwing errors we need to append try keyword as shown below.

Let’s call the class function on the object too as shown below.
swift try example

Swift try, try? and try!


So if you have any comments, questions, or recommendations, feel free to post them in the comment section below!

. . .

Leave a Comment

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

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home