0
0
Swiftprogramming~10 mins

Do-try-catch execution flow 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 call the function that might throw an error.

Swift
do {
    try [1]()
} catch {
    print("Error caught")
}
Drag options to blanks, or click blank then click option'
AriskyFunction
BsafeFunction
CprintError
DhandleError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function that does not throw with try.
Forgetting to use try before the function call.
2fill in blank
medium

Complete the code to catch a specific error type.

Swift
do {
    try riskyFunction()
} catch [1] {
    print("Specific error caught")
}
Drag options to blanks, or click blank then click option'
Alet error as NSError
Blet error as MyError
Clet error as String
Dlet error as Int
Attempts:
3 left
💡 Hint
Common Mistakes
Catching errors as the wrong type.
Using types that are not error types.
3fill in blank
hard

Fix the error in the catch block to properly handle the error.

Swift
do {
    try riskyFunction()
} catch {
    print([1])
}
Drag options to blanks, or click blank then click option'
Aerror.message
Berror
Cerror.description
Derror.localizedDescription
Attempts:
3 left
💡 Hint
Common Mistakes
Using properties that do not exist on the error object.
Printing the error object directly without description.
4fill in blank
hard

Fill both blanks to create a do-try-catch block that handles two different error types.

Swift
do {
    try riskyFunction()
} catch [1] {
    print("First error caught")
} catch [2] {
    print("Second error caught")
}
Drag options to blanks, or click blank then click option'
Alet error as MyError
Blet error as NSError
Clet error as String
Dlet error as Int
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-error types in catch blocks.
Mixing up the order of catch blocks.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps error codes to messages inside a do-try-catch block.

Swift
do {
    try riskyFunction()
} catch let error as [1] {
    let errorCode = error.code
    let errorMessages = [errorCode: [2]]
    print(errorMessages[[3]] ?? "Unknown error")
}
Drag options to blanks, or click blank then click option'
ANSError
Berror.localizedDescription
CerrorCode
DMyError
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong error types that don't have a code property.
Mixing keys and values in the dictionary.
Accessing the dictionary with wrong keys.