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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With