A. Missing do-catch block to handle the thrown error.
B. The function cannot throw NSError type errors.
C. The throw statement syntax is incorrect.
D. try keyword is not allowed with throwing functions.
Solution
Step 1: Check error handling usage
The code calls a throwing function with try but does not handle errors with do-catch or propagate with try? or try!.
Step 2: Confirm syntax correctness
The throw statement and function declaration are correct; the problem is missing error handling around the call.
Final Answer:
Missing do-catch block to handle the thrown error. -> Option A
Quick Check:
Throwing calls need error handling [OK]
Hint: Always handle errors from throwing functions with do-catch or try? [OK]
Common Mistakes:
Calling throwing functions without error handling
Confusing throw syntax with try syntax
Assuming try alone handles errors
5. You want to write a function loadData() that throws a custom error DataError.invalidFormat if data is bad. Which code correctly defines the error and throws it inside the function?
hard
A. class DataError: Error { case invalidFormat }
func loadData() throws {
throw DataError.invalidFormat
}
B. struct DataError { case invalidFormat }
func loadData() throws {
throw DataError.invalidFormat
}
C. enum DataError: Error { case invalidFormat }
func loadData() throws {
throw DataError.invalidFormat
}
D. enum DataError { case invalidFormat }
func loadData() throws {
throw DataError.invalidFormat
}
Solution
Step 1: Define a custom error type conforming to Error
In Swift, custom errors are usually enums conforming to the Error protocol, like enum DataError: Error.
Step 2: Throw the custom error inside the function
The function loadData() declares throws and throws DataError.invalidFormat correctly.
Final Answer:
enum DataError: Error { case invalidFormat }
func loadData() throws {
throw DataError.invalidFormat
} -> Option C
Quick Check:
Custom errors use enum + Error protocol [OK]
Hint: Use enum conforming to Error for custom errors [OK]
Common Mistakes:
Not conforming error type to Error protocol
Using struct or class without Error conformance
Forgetting throws keyword in function
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.