Error Handling Summary in Swift

Guard your code!

Mahmud Ahsan
Thinkdiff
Published in
3 min readDec 23, 2017

--

Photo by Zan on Unsplash

In short words, error handling is a safeguard for our code that handles the unexpected situation during the execution of a program that may crash and terminate the app from running.

In Swift, there are 4 ways to handle error:

  1. Propagate the error from function to calling code
  2. Using a do-catch statement
  3. Handle the error as an optional value
  4. Disabling error propagation

Let's define a custom error type. In Swift, errors are value type and conformed to the Error protocol.

1. Propagate the error from function to calling code

Let's define a throwing function. A throwing function is a function marked with keyword throws, it doesn’t handle the error itself rather propagate the error in calling scope.

throws keyword needs to place after the function parameter and before the return type.

Here sampleThrowError() function is called a throwing function because it can throw an error, it doesn’t handle error itself and the error must be handled by calling scope.

2. Using a do-catch statement

The error throwing function should be called within do block and a try keyword. Catch can handle a particular error and any error when no argument provided.

3. Handle the error…

--

--

I'm a software engineer passionate about web and mobile app development.