Swift Throw Statement

In swift, throw statement is used to stop current execution of functions or methods and throw error messages based on our requirements.

 

By using throw keyword in functions or methods we can throw errors based on our requirements in swift programming language.

 

In swift by using throws keyword with function or method declaration we can indicate that the defined method or function can throw an error. 

Syntax of Swift Throw Statement

Following is the syntax of using throws statement in function declaration to indicate that particular method can throw an error in a swift programming language.

 

func fucnName() throws -> String

func fucnName () -> String

Now we will see how to use throw statement in swift programming language with example.

Swift Throw Statement Example

Following is the simple example of using swift throw statement in function to return error message based on our conditions.

 

enum DividingErr : ErrorType {

case InvalidNumber

}

func divby(value: Int) throws -> Int {

guard value != else {

throw DividingErr.InvalidNumber

}

return 20 / value

}

let res = try! divby(3)

print(res)

If you observe above swift throw statement example we are throwing error in case if defined condition failed to satisfy based on our requirements.

 

When we run above throw statement example in swift playground that will return the result like as shown below.

 

6

This is how we can use throw statement in a swift programming language to throw errors in functions or methods based on our requirements.