Bird
Raised Fist0
Swiftprogramming~20 mins

Why error handling is explicit in Swift - Challenge Your Understanding

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!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift error handling code?

Consider this Swift code snippet that uses explicit error handling. What will be printed when this code runs?

Swift
enum FileError: Error {
    case fileNotFound
}

func readFile(_ filename: String) throws -> String {
    if filename == "exists.txt" {
        return "File content"
    } else {
        throw FileError.fileNotFound
    }
}

func test() {
    do {
        let content = try readFile("missing.txt")
        print(content)
    } catch {
        print("Error caught: \(error)")
    }
}
test()
AError caught: fileNotFound
BFile content
CRuntime error: uncaught error
DCompilation error: missing try keyword
Attempts:
2 left
💡 Hint

Think about what happens when the file name does not match "exists.txt" and how the error is handled.

🧠 Conceptual
intermediate
1:30remaining
Why does Swift require explicit error handling?

Why does Swift force programmers to handle errors explicitly using try, catch, or throws?

ATo make error handling clear and avoid unexpected crashes by forcing the programmer to acknowledge possible errors.
BBecause Swift does not support exceptions like other languages.
CTo reduce the size of compiled code by removing error handling automatically.
DBecause Swift only allows errors to be handled at runtime, not compile time.
Attempts:
2 left
💡 Hint

Think about the benefits of making error handling visible in code.

🔧 Debug
advanced
2:00remaining
What error does this Swift code produce?

Examine the following Swift code. What error will the compiler report?

Swift
func riskyOperation() throws -> Int {
    return 42
}

func test() {
    let result = riskyOperation()
    print(result)
}
test()
AError: Function must be marked with 'throws'
BRuntime error: uncaught error
CNo error, prints 42
DError: Call can throw but is not marked with 'try' and the error is not handled
Attempts:
2 left
💡 Hint

Check how functions that throw errors must be called.

🚀 Application
advanced
2:00remaining
How many errors are caught in this Swift code?

Given the following Swift code, how many errors will be caught and printed?

Swift
enum MyError: Error {
    case errorOne
    case errorTwo
}

func throwError(_ flag: Int) throws {
    switch flag {
    case 1: throw MyError.errorOne
    case 2: throw MyError.errorTwo
    default: return
    }
}

func testErrors() {
    for i in 0...2 {
        do {
            try throwError(i)
            print("No error for \(i)")
        } catch {
            print("Caught error for \(i): \(error)")
        }
    }
}
testErrors()
A1
B2
C3
D0
Attempts:
2 left
💡 Hint

Count how many times the throwError function throws an error in the loop.

❓ Predict Output
expert
2:30remaining
What is the output of this nested Swift error handling code?

Analyze this Swift code with nested error handling. What will be printed?

Swift
enum NetworkError: Error {
    case disconnected
}

enum DataError: Error {
    case corrupted
}

func fetchData() throws {
    throw NetworkError.disconnected
}

func processData() throws {
    do {
        try fetchData()
    } catch NetworkError.disconnected {
        throw DataError.corrupted
    }
}

do {
    try processData()
    print("Success")
} catch DataError.corrupted {
    print("Data error caught")
} catch {
    print("Other error caught")
}
AOther error caught
BSuccess
CData error caught
DRuntime crash
Attempts:
2 left
💡 Hint

Follow the error thrown and caught through the nested calls.

Practice

(1/5)
1. Why does Swift require error handling to be explicit using throws and try?
easy
A. To make sure programmers handle errors clearly and avoid unexpected crashes
B. To make the code run faster by skipping error checks
C. To hide errors from users automatically
D. To allow errors to be ignored silently

Solution

  1. Step 1: Understand Swift's error handling design

    Swift forces explicit error handling to make sure errors are noticed and managed properly.
  2. Step 2: Recognize the benefit of explicit handling

    This avoids unexpected crashes and makes programs more reliable and easier to maintain.
  3. Final Answer:

    To make sure programmers handle errors clearly and avoid unexpected crashes -> Option A
  4. Quick Check:

    Explicit error handling = clear, safe code [OK]
Hint: Explicit means you must handle errors clearly every time [OK]
Common Mistakes:
  • Thinking errors are handled automatically
  • Believing explicit handling slows down code
  • Confusing explicit with optional error handling
2. Which of the following is the correct way to call a function that can throw an error in Swift?
easy
A. let result = someFunction()
B. let result = try someFunction()
C. let result = throws someFunction()
D. let result = catch someFunction()

Solution

  1. Step 1: Recall Swift syntax for calling throwing functions

    Functions that can throw errors must be called with the try keyword.
  2. Step 2: Identify the correct syntax

    Only let result = try someFunction() uses the correct keyword try before the function call.
  3. Final Answer:

    let result = try someFunction() -> Option B
  4. Quick Check:

    Use try before throwing functions [OK]
Hint: Use 'try' before calling throwing functions [OK]
Common Mistakes:
  • Omitting 'try' when calling throwing functions
  • Using 'throws' instead of 'try' when calling
  • Using 'catch' incorrectly in function calls
3. What will be the output of this Swift code?
func canThrow() throws -> String {
  return "Success"
}

func test() {
  do {
    let result = try canThrow()
    print(result)
  } catch {
    print("Error caught")
  }
}
test()
medium
A. Success
B. Error caught
C. No output
D. Compile error

Solution

  1. Step 1: Analyze the throwing function behavior

    The function canThrow() is marked as throwing but always returns "Success" without throwing an error.
  2. Step 2: Understand the do-catch block execution

    The try succeeds, so print(result) prints "Success" and the catch block is skipped.
  3. Final Answer:

    Success -> Option A
  4. Quick Check:

    try succeeds, prints result [OK]
Hint: If no error thrown, do-catch prints success path [OK]
Common Mistakes:
  • Assuming catch runs even if no error
  • Thinking throws always cause errors
  • Expecting compile error without catch
4. Identify the error in this Swift code snippet:
func risky() throws -> Int {
  return 42
}

let value = risky()
medium
A. Cannot assign function result to a constant
B. Function must return a String, not Int
C. Missing 'throws' keyword in function declaration
D. Missing 'try' keyword when calling a throwing function

Solution

  1. Step 1: Check function declaration and call

    The function risky() is declared with throws, so it can throw errors.
  2. Step 2: Verify calling syntax

    Calling a throwing function requires the try keyword, which is missing here.
  3. Final Answer:

    Missing 'try' keyword when calling a throwing function -> Option D
  4. Quick Check:

    Call throwing functions with 'try' [OK]
Hint: Always use 'try' when calling throwing functions [OK]
Common Mistakes:
  • Calling throwing functions without 'try'
  • Confusing return types
  • Ignoring function's throws declaration
5. You want to write a Swift function that reads a file and returns its content as a String. The file reading can fail. How should you design this function to follow Swift's explicit error handling?
hard
A. Use do-catch inside the function but do not mark it with throws
B. Return an optional String and ignore errors silently
C. Declare the function with throws and use try when calling file reading methods
D. Catch errors inside the function and print them, then return an empty String

Solution

  1. Step 1: Understand Swift's explicit error handling philosophy

    Functions that can fail should be marked with throws to force callers to handle errors explicitly.
  2. Step 2: Apply correct design for file reading

    The function should declare throws and use try when calling file reading methods that can throw errors.
  3. Final Answer:

    Declare the function with throws and use try when calling file reading methods -> Option C
  4. Quick Check:

    Use throws and try for error propagation [OK]
Hint: Mark throwing functions with 'throws' and call with 'try' [OK]
Common Mistakes:
  • Ignoring errors by returning optionals
  • Catching errors inside without propagating
  • Returning empty strings on failure silently
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