CODEX

Swift — Try, Try! or Try?

Learn the three ways of handling errors in Swift

Artturi Jalli
CodeX
Published in
3 min readFeb 2, 2021

--

Swift supports error handling natively which is amazing. But what might be a bit confusing is there are three different try statements: try, try?, and try! for handling errors.

Let’s go through how to handle errors with each.

Examples—Try, Try?, and Try!

In the examples, we are parsing a username such that we throw an error if the length of the name exceeds 20 characters. If the name is shorter we return the name itself.

Before we can throw errors, we need an error case for too long names:

enum NameError: Error {
case tooLong
}

Next, let’s write a parser that throws errors on too long usernames:

func parseName(_ name: String) throws -> String {
if name.count > 20 {
throw NameError.tooLong
} else {
return name
}
}

Now we have the error throwing functionality in place and we are ready to demonstrate handling errors in three different ways using trye, try? and try!.

Try

With try we cannot call try parseName("Nick"). We need to use the Do-Try-Catch structure instead whose syntax looks…

--

--

Artturi Jalli
CodeX
Writer for

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)