Throw and catch exceptions


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


// 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 {

// 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")


Find answers here

Hi there! Ask Us a Question We are ready to help