In this tutorial you will learn about the Swift Throw Statement and its application with practical example.
Swift Throw Statement
In swift, the throw statement is an error handling statement. The throw statement allows function to stop the execution and throw an error if there is any exception or error occurs. In Swift, if a function, method, or an initializer can throw an error, it must be added throws keyword in its definition after the parameter list and before the return type.
If a function or an initializer can throw an error, the throws modifier must be added in the definition itself right after the paratheses and just before the return type (->).
Syntax:-
1 2 3 |
func canThrowErrors() throws -> <Return Type> { } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
enum errorInfo: Error { case noValidName case noValidAge } func empInfo(empAge: Int, empName: String) throws { guard empAge > 0 else{ throw errorInfo.noValidAge } guard empName.count > 0 else{ throw errorInfo.noValidName } } print("W3Adda - Swift throw statement") do{ try empInfo(empAge: -1, empName: "") } catch let error { print("Error: \(error)") } |
When we run the above swift program, we see the following output –
Output:-