sriram hegde
sriram hegde

Reputation: 2471

How to make a Swift 2 function throw exception

Here is my current code

class HelloWorld {
    func foobar() {
        // ...
    }
}

How do I make this function throw exception when its called and something unexpected happens?

Upvotes: 5

Views: 4728

Answers (2)

Unome
Unome

Reputation: 6900

According to the Swift documentation:

Throwing Errors

To indicate that a function or method can throw an error, you write the throws keyword in its declaration, after its parameters. If it specifies a return type, you write the throws keyword before the return arrow (->). A function, method, or closure cannot throw an error unless explicitly indicated.

There is a wealth of info about this topic here in Apple's documentation

Error's are represented using enums, so create some error you would like via an enum and then use the throw keyword to do it.

example:

enum MyError: ErrorType{
    case FooError
}

func foobar() throws{
   throw MyError.FooError
}

Upvotes: 11

Jojodmo
Jojodmo

Reputation: 23616

First, you can create an enum that contains your errors, and implements the ErrorType protocol

enum MyError: ErrorType{
    case Null
    case DivisionByZero
}

Then, you can call your errors using throw

throw MyError.DivisionByZero

So, a division function could look like this

func divide(x: Int, y: Int) throws -> Float{
    if(y == 0){
        throw MyError.DivisionByZero
    }
    else{
        return x / y
    }
}

Upvotes: 7

Related Questions