Swift Throw Statement

  Total Views : 361
  Comments : 0
  Keywords : Swift throw statement to throw an error in functions or methods with examples, Swift handle errors in function or methods using throw statement with example.

Here we will learn throw statement in swift with example and how to use swift throw statement to throw an errors in functions or methods based on our requirements with examples.

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 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 swift programming language to throw errors in functions or methods based on our requirements. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User