Sometimes a function might fail to do its job. Using throws lets the function tell you when something goes wrong.
Throwing functions with throws in Swift
func functionName() throws -> ReturnType { // code that might throw an error }
Use throws after the function parentheses to mark it as a throwing function.
Calling a throwing function requires handling errors with try.
func readFile() throws -> String { // might throw an error if file not found return "file content" }
enum DivisionError: Error { case divisionByZero } func divide(_ a: Int, by b: Int) throws -> Int { if b == 0 { throw DivisionError.divisionByZero } return a / b }
This program defines a throwing function divide that throws an error if dividing by zero. It then calls this function twice: once with valid input and once with zero as the divisor. The errors are caught and handled with do-catch.
enum DivisionError: Error { case divisionByZero } func divide(_ a: Int, by b: Int) throws -> Int { if b == 0 { throw DivisionError.divisionByZero } return a / b } // Using the throwing function func testDivision() { do { let result = try divide(10, by: 2) print("Result: \(result)") } catch DivisionError.divisionByZero { print("Error: Cannot divide by zero.") } catch { print("Unexpected error: \(error)") } do { let result = try divide(10, by: 0) print("Result: \(result)") } catch DivisionError.divisionByZero { print("Error: Cannot divide by zero.") } catch { print("Unexpected error: \(error)") } } testDivision()
Throwing functions must be called with try, try?, or try!.
Use do-catch blocks to handle errors gracefully.
Errors must conform to the Error protocol.
Use throws to mark functions that can fail.
Call throwing functions with try and handle errors with do-catch.
Define errors by creating types that conform to Error.
Practice
throws keyword indicate when used in a Swift function declaration?Solution
Step 1: Understand the role of
Thethrowsthrowskeyword marks a function that can produce an error during execution.Step 2: Recognize error handling requirement
Calling athrowsfunction requires handling the possible error withtryanddo-catch.Final Answer:
The function can produce an error that must be handled. -> Option CQuick Check:
throwsmeans function can throw error [OK]
- Thinking throws means async function
- Assuming throws means function returns Bool
- Confusing throws with access control keywords
Solution
Step 1: Recall correct syntax for throwing functions
In Swift,throwscomes after the parentheses and before the return type.Step 2: Match syntax with options
func fetchData() throws -> String matches the correct syntax:func name() throws -> ReturnType.Final Answer:
func fetchData() throws -> String -> Option DQuick Check:
Correct syntax isthrowsafter () [OK]
- Writing throw instead of throws
- Placing throws after return type
- Omitting throws keyword
enum FileError: Error {
case notFound
}
func readFile() throws -> String {
throw FileError.notFound
}
do {
let content = try readFile()
print(content)
} catch {
print("Error occurred")
}Solution
Step 1: Analyze the throwing function behavior
The functionreadFile()always throwsFileError.notFounderror.Step 2: Understand the do-catch block
ThetrycallsreadFile(), which throws, so control moves tocatchblock printing "Error occurred".Final Answer:
Error occurred -> Option BQuick Check:
Thrown error triggers catch printing message [OK]
- Expecting thrown error value to print
- Ignoring that error causes catch block
- Thinking no output occurs
func riskyOperation() throws -> Int {
return 42
}
let result = riskyOperation()
print(result)Solution
Step 1: Check calling syntax for throwing functions
Calling a function marked withthrowsrequires usingtrykeyword.Step 2: Identify missing try keyword
The code callsriskyOperation()withouttry, causing a compile error.Final Answer:
Missing try keyword when calling riskyOperation() -> Option AQuick Check:
Throwing functions need try when called [OK]
- Calling throws function without try
- Assuming throws means no return value
- Forgetting to handle errors with do-catch
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?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 declaresthrowsafter 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 } usesguard letto safely unwrap Int, throwingParseError.invalidFormatif conversion fails.Final Answer:
Correctly implements throwing function with error handling. -> Option AQuick Check:
Throws declared and error thrown on invalid input [OK]
- Not marking function with throws
- Throwing error outside throws function
- Returning default instead of throwing error
Ready to prove it?
Pass the test and this pattern moves unknown
