Throw or Rethrow that Error?

Deal with that Error

Steven Curtis

--

Photo by Mohamed Nohassi on Unsplash

Error handling in Swift has come a long way. But wait, there are throws and rethrows keywords? What's going on?

An in-depth look into the two types of closures, focussing on @escaping and @nonescaping closures.

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.4.1, and Swift 5.2.2

The example

Imagine a function that adds stuff to Strings (This is a convoluted example, people!).

We are going to use the following CustomError to make things clear

Click for Gist

The requirements are that we have a function that takes a name and function that takes a String and returns a String. This function that we take, however, can throw an error. This leads to our outer function being able to return an error itself.

Already the language of outer function starts to get a little confusing. In steps the code snippet!

Click for Gist

of interest is the addHelloWorld function - this can throw so the throws keyword is placed before the -> symbol, and within the function we do indeed throw a CustomError.

This is reflected in the func stringBuilder(name: String, closure: (String) throws -> (String)) rethrows function signature - first because the closure parameter as (String) throws -> (String) allows the contained function to throw. However, there is another part of this - the final keyword rethrows is because the function in the parameter throws - stringBuilder does not throw an error itself.

Let us get confused

You know the statements above? They are all correct! This means that we are all set.

But what if stringBuilder can throw an error?

It sounds simple — we can replace the rethrows keyword with throws.

--

--