Bird
Raised Fist0
iOS Swiftmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the try keyword do in Swift error handling?
easy
A. It catches an error thrown by a function.
B. It calls a function that might throw an error and requires handling.
C. It defines a new error type.
D. It throws an error manually.

Solution

  1. Step 1: Understand the role of try

    The try keyword is used before calling a function that can throw an error, signaling that error handling is needed.
  2. Step 2: Differentiate from other keywords

    catch handles errors, throw raises errors, and defining errors uses enum or struct.
  3. Final Answer:

    It calls a function that might throw an error and requires handling. -> Option B
  4. Quick Check:

    try calls throwing functions [OK]
Hint: Remember: try calls, catch handles, throw creates errors [OK]
Common Mistakes:
  • Confusing try with catch or throw keywords
  • Thinking try itself catches errors
  • Using try without a throwing function
2. Which of the following is the correct syntax to catch an error in Swift?
easy
A. do { try someFunction() } catch { print("Error") }
B. try { someFunction() } catch { print("Error") }
C. catch { try someFunction() }
D. do catch { try someFunction() }

Solution

  1. Step 1: Recall the correct do-catch syntax

    In Swift, error handling uses do { try ... } catch { ... } blocks to catch errors.
  2. Step 2: Identify the correct option

    do { try someFunction() } catch { print("Error") } correctly wraps the try call inside a do block followed by a catch block.
  3. Final Answer:

    do { try someFunction() } catch { print("Error") } -> Option A
  4. Quick Check:

    do-catch syntax = do { try someFunction() } catch { print("Error") } [OK]
Hint: Remember: do { try } catch { } is the pattern [OK]
Common Mistakes:
  • Placing try outside do block
  • Using catch without do
  • Incorrect order of try and catch
3. What will be printed when running this Swift code?
enum FileError: Error { case notFound }
func readFile() throws {
  throw FileError.notFound
}
do {
  try readFile()
  print("File read successfully")
} catch {
  print("Failed to read file")
}
medium
A. Compile error
B. File read successfully
C. No output
D. Failed to read file

Solution

  1. Step 1: Analyze the throwing function

    The function readFile() always throws FileError.notFound, so it never completes normally.
  2. Step 2: Understand the do-catch behavior

    The try readFile() call throws an error, so control jumps to the catch block, printing "Failed to read file".
  3. Final Answer:

    Failed to read file -> Option D
  4. Quick Check:

    Thrown error triggers catch block [OK]
Hint: Thrown error skips try block print, runs catch print [OK]
Common Mistakes:
  • Assuming code after try runs if error thrown
  • Thinking no output if error thrown
  • Confusing error throwing with returning
4. Identify the error in this Swift code snippet:
func riskyFunction() throws {
  throw NSError(domain: "Error", code: 1)
}
try riskyFunction()
medium
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

  1. 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!.
  2. Step 2: Confirm syntax correctness

    The throw statement and function declaration are correct; the problem is missing error handling around the call.
  3. Final Answer:

    Missing do-catch block to handle the thrown error. -> Option A
  4. 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

  1. 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.
  2. Step 2: Throw the custom error inside the function

    The function loadData() declares throws and throws DataError.invalidFormat correctly.
  3. Final Answer:

    enum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat } -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard