0
0
Swiftprogramming~10 mins

Throwing functions with throws in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function that can throw an error.

Swift
func checkNumber(_ number: Int) [1] {
    if number < 0 {
        throw NSError(domain: "Negative number", code: 1)
    }
}
Drag options to blanks, or click blank then click option'
Athrow
Bthrows
Ctry
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throw' instead of 'throws' in the function declaration.
Confusing 'try' with the function declaration keyword.
2fill in blank
medium

Complete the code to call a throwing function using the correct keyword.

Swift
do {
    try [1](5)
} catch {
    print("Error occurred")
}
Drag options to blanks, or click blank then click option'
Athrow
Bthrows
CcheckNumber
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throws' or 'throw' instead of the function name.
Omitting the 'try' keyword before the function call.
3fill in blank
hard

Fix the error in the function declaration to properly indicate it can throw errors.

Swift
func validateAge(_ age: Int) [1] {
    if age < 18 {
        throw NSError(domain: "Too young", code: 2)
    }
}
Drag options to blanks, or click blank then click option'
Athrow
Bcatch
Ctry
Dthrows
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throw' instead of 'throws' in the function declaration.
Confusing 'try' with the declaration keyword.
4fill in blank
hard

Fill both blanks to create a throwing function and call it correctly.

Swift
func [1](_ value: Int) [2] {
    if value == 0 {
        throw NSError(domain: "Zero value", code: 3)
    }
}
Drag options to blanks, or click blank then click option'
Athrows
BcheckValue
Cthrow
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the function name and 'throws' keyword.
Using 'throw' instead of 'throws'.
5fill in blank
hard

Fill all three blanks to declare a throwing function, call it with try, and handle errors.

Swift
func [1](_ input: String) [2] {
    if input.isEmpty {
        throw NSError(domain: "Empty input", code: 4)
    }
}

do {
    [3] [1]("")
} catch {
    print("Caught an error")
}
Drag options to blanks, or click blank then click option'
AprocessInput
Bthrows
Ctry
Dthrow
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throw' instead of 'throws' in the declaration.
Omitting 'try' when calling the function.