Swift try catch example: how to do error handling in swift

In this new swift tutorial you'll learn how to use the new swift 2 try catch syntax, to perform error handling. You'll learn how to use the try, catch, throws, enum and guard statement in order to perform a good error handling approach.

Error handling allows you to avoid the crash of your application, due to some wrong situation, like wrong input format.

Enum declaration: let's define the error types

Through the enum ErrorType you'll able to define all the errors your application can generate in a very simple way.

enum Error: ErrorType
	case your_error_name_1
	case your_error_name_2(some_input:String)

 In this way you'll can define all the possible error cases that your application can generate, in order to manage them and avoid crashes. As you can see you'll able also to define some inputs that your throws declaration can send.

Guard statement: let's check about the right data format

The Guard statement is able to check the input values. If the conditions of the guard statement are not statisfied, you can perform the error propagation using the throw statement.

Here is an example of the use of the guard statement, in order to check the right inputs type.

guard let _:CGFloat = n1, let _:CGFloat = n2 else
	//the inputs are not of CGFloat type

Error propagation: how to use the throw declaration to propagate the error

In order to propagate the errors, you'll have to define the right outputs of the function, in this way:

func your_function() throws -> data_output_type
	throw Error.Your Error Type

As you can see, the error is marked with the throws declaration before the output type, in this way you tell swift that this function is able to perform the error propagation.

At every line inside your function, where you need to propagate the error and stop the current function, you'll just have to call the throw statament with the error type your function is generating.

How to handle the error: do try catch statements

 When you have to call the function that can throws an error, you'll have to call the do , try and catch statement.

Inside the Do statement you'll have to use the try function before calling the function that can throws an error. This will let know Swift that that's the function that can generate an error. Finally inside the catch statement you'll define the bahaviour in case of Error.
Here is how the do..try..catch statemetes should look like:

	result = try your_throwable_function()
catch Error.Some Error type
	//do some error handling with Error Type
	//do error handling with unkown error

Inside the catch statement you can block your code execution and put some alert dialog to inform the users that something went wrong.

here you can download the error handling example project: download



Leave a comment