Challenge - 5 Problems
Swift Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate2:00remaining
What error does this Swift code produce?
Consider this Swift code snippet that tries to throw an error without marking the function as throwing. What error will the compiler show?
iOS Swift
func testError() {
throw NSError(domain: "Test", code: 1, userInfo: nil)
}Attempts:
2 left
💡 Hint
In Swift, only functions marked with 'throws' can throw errors.
✗ Incorrect
The function 'testError' is not marked with 'throws', but it tries to throw an error. Swift requires functions that throw errors to be explicitly marked with 'throws'.
📝 Syntax
intermediate2:00remaining
What error does this Swift code produce?
Consider this Swift code snippet that calls a throwing function with 'try' without handling the error. What will the compiler show?
iOS Swift
func mightFail() throws {
throw NSError(domain: "Fail", code: 1, userInfo: nil)
}
try mightFail()Attempts:
2 left
💡 Hint
Swift requires explicit error handling ('do-catch', 'try?', or 'try!') for calls to throwing functions.
✗ Incorrect
The code uses 'try mightFail()' without handling the potential error (no 'do-catch', 'try?', or 'try!'). Swift compiler enforces error handling, resulting in a compile-time error like 'Errors thrown from here are not handled'.
🧠 Conceptual
advanced2:00remaining
Which option correctly uses 'try?' to handle errors?
Given a throwing function, which code snippet safely calls it and returns nil if an error occurs?
iOS Swift
func fetchData() throws -> String {
throw NSError(domain: "Data", code: 404, userInfo: nil)
}Attempts:
2 left
💡 Hint
'try?' converts errors to nil instead of throwing.
✗ Incorrect
'try?' calls a throwing function and returns an optional. If an error occurs, it returns nil instead of throwing.
❓ lifecycle
advanced2:00remaining
What is the output of this Swift error handling code?
Analyze the output printed by this code snippet:
iOS Swift
enum SampleError: Error {
case failed
}
func test() throws {
throw SampleError.failed
}
do {
try test()
print("Success")
} catch {
print("Caught error")
}
print("Done")Attempts:
2 left
💡 Hint
The error thrown is caught in the catch block.
✗ Incorrect
The function 'test' throws an error. The 'do' block tries to call it, but the error is caught, so 'Caught error' is printed. Then 'Done' is printed after the do-catch.
🔧 Debug
expert2:00remaining
Why does this Swift code cause a runtime crash?
Examine this code and identify why it crashes at runtime:
iOS Swift
func risky() throws -> String {
throw NSError(domain: "Crash", code: 1, userInfo: nil)
}
let result = try! risky()
print(result)Attempts:
2 left
💡 Hint
'try!' assumes no error will occur and crashes if one does.
✗ Incorrect
'try!' unwraps the result forcefully. If the function throws an error, the app crashes at runtime.