📖 Scenario: Imagine you are building a simple app that checks if a password is strong enough. If the password is too short, the app should tell the user with an error.
🎯 Goal: You will create a throwing function that checks password length and throws an error if the password is too short. Then you will call this function and handle the error.
📋 What You'll Learn
Create an enum called PasswordError that conforms to Error with a case tooShort
Create a throwing function called checkPassword that takes a String parameter password
Inside checkPassword, throw PasswordError.tooShort if the password length is less than 8
Call checkPassword inside a do-catch block with the password "abc123"
Print "Password is strong enough" if no error is thrown
Print "Password is too short" if PasswordError.tooShort is caught
💡 Why This Matters
🌍 Real World
Throwing functions are used in apps to handle unexpected problems like invalid input or failed network calls. This helps apps respond gracefully instead of crashing.
💼 Career
Understanding how to write and handle throwing functions is important for Swift developers to build robust and user-friendly applications.
Progress0 / 4 steps
1
Create the PasswordError enum
Create an enum called PasswordError that conforms to Error with a case called tooShort.
Swift
Hint
Use enum PasswordError: Error { case tooShort } to define the error type.
2
Create the throwing function checkPassword
Create a throwing function called checkPassword that takes a String parameter named password. Inside the function, throw PasswordError.tooShort if password.count is less than 8.
Swift
Hint
Define the function with throws and use throw PasswordError.tooShort inside an if check.
3
Call checkPassword inside a do-catch block
Write a do-catch block that calls checkPassword with the password "abc123". In the do block, call checkPassword("abc123"). In the catch block, catch PasswordError.tooShort specifically.
Swift
Hint
Use do { try checkPassword("abc123") ... } catch PasswordError.tooShort { ... } to handle the error.
4
Print the result
Run the program to print the result of the password check. The output should be "Password is too short" because the password "abc123" has less than 8 characters.
Swift
Hint
Run the code and check the console output.
Practice
(1/5)
1. What does the throws keyword indicate when used in a Swift function declaration?
easy
A. The function cannot be called outside its module.
B. The function always returns a Boolean value.
C. The function can produce an error that must be handled.
D. The function runs asynchronously.
Solution
Step 1: Understand the role of throws
The throws keyword marks a function that can produce an error during execution.
Step 2: Recognize error handling requirement
Calling a throws function requires handling the possible error with try and do-catch.
Final Answer:
The function can produce an error that must be handled. -> Option C
Quick Check:
throws means function can throw error [OK]
Hint: Throws means function can fail and needs error handling [OK]
Common Mistakes:
Thinking throws means async function
Assuming throws means function returns Bool
Confusing throws with access control keywords
2. Which of the following is the correct way to declare a throwing function in Swift?
easy
A. func fetchData() -> throws String
B. func fetchData() throw -> String
C. func fetchData() throws String
D. func fetchData() throws -> String
Solution
Step 1: Recall correct syntax for throwing functions
In Swift, throws comes after the parentheses and before the return type.
func riskyOperation() throws -> Int {
return 42
}
let result = riskyOperation()
print(result)
medium
A. Missing try keyword when calling riskyOperation()
B. Function should not return Int
C. Throws keyword is not allowed here
D. Missing catch block after function call
Solution
Step 1: Check calling syntax for throwing functions
Calling a function marked with throws requires using try keyword.
Step 2: Identify missing try keyword
The code calls riskyOperation() without try, causing a compile error.
Final Answer:
Missing try keyword when calling riskyOperation() -> Option A
Quick Check:
Throwing functions need try when called [OK]
Hint: Use try when calling throws functions [OK]
Common Mistakes:
Calling throws function without try
Assuming throws means no return value
Forgetting to handle errors with do-catch
5. You want to write a function parseNumber(from: String) that throws an error if the string is not a valid integer. Which of the following implementations correctly uses throws and error handling?
hard
A. enum ParseError: Error { case invalidFormat }
func parseNumber(from text: String) throws -> Int {
guard let number = Int(text) else {
throw ParseError.invalidFormat
}
return number
}
B. func parseNumber(from text: String) -> Int {
if Int(text) == nil {
print("Invalid format")
}
return Int(text) ?? 0
}
C. enum ParseError: Error { case invalidFormat }
func parseNumber(from text: String) -> Int throws {
if Int(text) == nil {
throw ParseError.invalidFormat
}
return Int(text)!
}
D. func parseNumber(from text: String) throws -> Int {
if Int(text) == nil {
return 0
}
return Int(text)!
}
Solution
Step 1: Check function signature and error throwing
enum ParseError: Error { case invalidFormat }
func parseNumber(from text: String) throws -> Int {
guard let number = Int(text) else {
throw ParseError.invalidFormat
}
return number
} correctly declares throws after parameters and before return type, and throws error if parsing fails.
Step 2: Verify error throwing logic
enum ParseError: Error { case invalidFormat }
func parseNumber(from text: String) throws -> Int {
guard let number = Int(text) else {
throw ParseError.invalidFormat
}
return number
} uses guard let to safely unwrap Int, throwing ParseError.invalidFormat if conversion fails.
Final Answer:
Correctly implements throwing function with error handling. -> Option A
Quick Check:
Throws declared and error thrown on invalid input [OK]
Hint: Use guard and throw error inside throws function [OK]
Common Mistakes:
Not marking function with throws
Throwing error outside throws function
Returning default instead of throwing error
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.