Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 689
sriram hegde Avatar asked Aug 13 '15 16:08

sriram hegde


2 Answers

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
}
like image 152
Unome Avatar answered Nov 09 '22 17:11

Unome


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
    }
}
like image 7
Jojodmo Avatar answered Nov 09 '22 19:11

Jojodmo