Throw and catch exceptions

 Problem

I want to create a functions that throws an error and then be able to "catch" it, using a Do-Catch statement.



 Recipe


// Declare our error type
enum MyError: ErrorType {
    case NumberIsLower
    case NumberIsGreater
}

// Declare a function 
// that throws an exception
func testFunc(a: Int) throws {
    if a<10 {
        throw MyError.NumberIsLower
    }
    else if a>10 {
        throw MyError.NumberIsGreater
    }
    else {
        print("Great!")
    }
}

// Try calling it
// and catch all possible exceptions
do {
    try testFunc(5)
}
catch MyError.NumberIsLower {
    print("Ooops! Number was lower than 10")
}
catch MyError.NumberIsGreater {
    print("Ooops! Number was greater than 10")
}
				

Heard the news?

The Swift Cookbook for Swift 3 is at last here! For iBooks, Kindle and Paperback.
Hurry up - and Check it out! ;-)

 

 Playground