简体   繁体   中英

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?

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
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM