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.
Through the enum ErrorType you'll able to define all the errors your application can generate in a very simple way.
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.
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.
In order to propagate the errors, you'll have to define the right outputs of the function, in this way:
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.
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:
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