Throwing Errors in swift 3

ref – http://www.techotopia.com/index.php/Understanding_Error_Handling_in_Swift_2

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Representing and Throwing Errors

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Handling Errors

When an error is thrown, some surrounding piece of code must be responsible for handling the error—for example, by correcting the problem, trying an alternative approach, or informing the user of the failure.

There are four ways to handle errors in Swift:
– You can propagate the error from a function to the code that calls that function
– handle the error using a do-catch statement
– handle the error as an optional value
– or assert that the error will not occur.

Propagate the error from a function to the code that calls that function

A throwing function propagates errors that are thrown inside of it to the scope from which it’s called.
hence, say our function fileTransfer throws an error.

We are call a throwing function with try phrase inside a do/try, where the catch code catches any errors thrown from the do function.

Only throwing functions can propagate errors. Any errors thrown inside a nonthrowing function must be handled inside the function.

example:

by default, in order to run the throw catch mechanism in order to handle the error, we use do-catch statement.

Full SOURCE CODE

OUTPUT:

—— fileTransfer function ———
fileTransfer – THROW NO CONNECTION!
clean THIS up! 😀
clean THAT up! 😀
CAUGHT —– NO CONNECTION!——
DONE!

Notice how our file transfer function runs first. Then right before it throws, it will call the defer functions.

After the defer functions are done executing, the exception is thrown and consequently, caught.