Error handling using throws and do-catch in Swift

Example of using throws and do-catch and try to handle errors in Swift

Throwing functions in Swift



To indicate that a function can throw error you just add the word “throws” after its parameters and before its return type.

It is then called a throwing function.

To give an example lets first create a non-throwing function that check the age like this:

    func myNonThrowingFunction(age: Int)
    {
        if age < 16 
        { 
            print("you must be over 16 to use this function")     
        }       
        else if age > 22
        {
            print("you must be under 22 to use this function")
        }
        else
        {
            print("Enjoy......")
        }
    }
    

Now we will implement the same function but we will make it a throwing function.

But there is a little step we need to do first, we will create an enum for our age errors like that

enum AgeError: Error {
    case MaxAge
    case MinAge
}

Then we can use it in our throwing function

    func myThrowingFunction(age: Int) throws
    {
        if age < 16 
        { 
            throw AgeError.MinAge 
        }
        else if age > 22
        {
            throw AgeError.MaxAge
        }
        else
        {
            print("Enjoy......")
        }
    }

Using do-catch and try to handle Errors

After we defined our throwing function it is time to call it and handle the errors it throws.

We will do that by using a try inside a do-catch block

        do
        {
            try myThrowingFunction(age: 12)
        }
        catch AgeError.MaxAge
        {
            print("max age error")
        }
        catch AgeError.MinAge
        {
            print("min age error")
        }
        catch
        {
            print("unexpected error: \(error.localizedDescription)")
        }

Propagating Errors

Only throwing functions can propagate errors occurred inside it to the scope from where it was called

Non-throwing function must handle its errors inside it.

try or try? or try!

try -> must be used inside a do-catch block.

try! -> disables error propagating, use only if you are 100% sure that no error will be thrown, if an error occurred you will get a runtime error

let photo = try! loadImage(atPath: "./Resources/ios_tutorial_logo.jpg")

try? -> will convert try into optional that returns nil if error is thrown like this:

let x = try? someThrowingFunction()

Leave a Reply

Your email address will not be published. Required fields are marked *