CODEX

Swift 5: Error Handling in 2022 [Made Simple]

Learn why, when, and how to use error handling in your applications.

Artturi Jalli
CodeX
Published in
4 min readFeb 1, 2021

--

Photo by Conor Samuel on Unsplash

Swift Error Handling

According to Apple Developer Docs:

Error handling is the process of responding to and recovering from error conditions in your program

Error Throwing Functions in Swift

In Swift, functions can throw errors. A function is made throw an error if it is not capable of resolving the error itself. When an error is thrown, it is caught and handled by the code that calls the function. This behavior is called error propagation.

Working with error throwing functions requires extra carefulness to be sure to catch the errors. Thus, a Do-Try-Catch structure is needed when dealing with error throwing functions:

do {
try throwing_expression
} catch error_type {
handle_error
}

This is the basic structure for error handling in Swift.

The above code skeleton simply translates to “Try running the function and catch certain types of errors that the function might throw”.

--

--

Artturi Jalli
CodeX

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