0
0
iOS Swiftmobile~20 mins

Error handling (try, catch, throw) in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate
2: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)
}
ACompile-time error: missing catch block
BRuntime error: unhandled exception
CNo error, code runs fine
DCompile-time error: 'throw' used in non-throwing function
Attempts:
2 left
💡 Hint
In Swift, only functions marked with 'throws' can throw errors.
📝 Syntax
intermediate
2: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()
AProgram crashes with a runtime error
BCompiler forces you to handle the error
CError is ignored and program continues
DProgram logs the error but continues
Attempts:
2 left
💡 Hint
Swift requires explicit error handling ('do-catch', 'try?', or 'try!') for calls to throwing functions.
🧠 Conceptual
advanced
2: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)
}
Alet result = try? fetchData()
Blet result = try fetchData() catch { return nil }
Clet result = fetchData()
Dlet result = try! fetchData()
Attempts:
2 left
💡 Hint
'try?' converts errors to nil instead of throwing.
lifecycle
advanced
2: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")
A
Caught error
Done
B
Success
Done
C
Done
Caught error
DCaught error
Attempts:
2 left
💡 Hint
The error thrown is caught in the catch block.
🔧 Debug
expert
2: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)
AThe function is not marked with 'throws'
BMissing 'do-catch' block causes syntax error
CUsing 'try!' forces a crash if an error is thrown
DThe error is caught but ignored
Attempts:
2 left
💡 Hint
'try!' assumes no error will occur and crashes if one does.