0
0
Swiftprogramming~20 mins

Why error handling is explicit in Swift - Challenge Your Understanding

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!
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.