Complete the code to call the function that might throw an error.
do {
try [1]()
} catch {
print("Error caught")
}The try keyword is used before calling a function that can throw an error. Here, riskyFunction() is the function that might throw.
Complete the code to catch a specific error type.
do {
try riskyFunction()
} catch [1] {
print("Specific error caught")
}To catch a specific error type, you use catch let error as MyError. This matches errors of type MyError.
Fix the error in the catch block to properly handle the error.
do {
try riskyFunction()
} catch {
print([1])
}Inside a catch block, error.localizedDescription gives a readable message about the error.
Fill both blanks to create a do-try-catch block that handles two different error types.
do {
try riskyFunction()
} catch [1] {
print("First error caught")
} catch [2] {
print("Second error caught")
}The first catch handles MyError type errors, the second handles NSError type errors.
Fill all three blanks to create a dictionary comprehension that maps error codes to messages inside a do-try-catch block.
do {
try riskyFunction()
} catch let error as [1] {
let errorCode = error.code
let errorMessages = [errorCode: [2]]
print(errorMessages[[3]] ?? "Unknown error")
}The catch block catches NSError. The dictionary maps errorCode to error.localizedDescription. The print statement accesses the message by errorCode.