0
0
Swiftprogramming~20 mins

Do-try-catch execution flow in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Do-Try-Catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of do-try-catch with successful try
What is the output of this Swift code snippet?
Swift
enum SampleError: Error {
    case fail
}

func testFunc() throws -> String {
    return "Success"
}

do {
    let result = try testFunc()
    print(result)
} catch {
    print("Error caught")
}
AError caught
BSuccess
CNo output
DCompilation error
Attempts:
2 left
💡 Hint
The function does not throw an error, so the catch block is skipped.
Predict Output
intermediate
2:00remaining
Output when try throws an error
What will this Swift code print?
Swift
enum SampleError: Error {
    case fail
}

func testFunc() throws -> String {
    throw SampleError.fail
}

do {
    let result = try testFunc()
    print(result)
} catch {
    print("Error caught")
}
ASuccess
BNo output
CRuntime crash
DError caught
Attempts:
2 left
💡 Hint
The function throws an error, so the catch block runs.
🔧 Debug
advanced
2:00remaining
Identify the error in do-try-catch usage
What error does this Swift code produce when compiled?
Swift
func testFunc() throws -> String {
    return "Hello"
}

let result = try testFunc()
print(result)
ACompile-time error: 'try' must be used inside a 'do' block or marked with 'try?' or 'try!'
BRuntime error: uncaught error
CNo error, prints 'Hello'
DCompile-time error: missing catch block
Attempts:
2 left
💡 Hint
In Swift, 'try' must be inside a do-catch or handled with try? or try! outside.
🧠 Conceptual
advanced
2:00remaining
Behavior of multiple catch blocks
Given this Swift code, which catch block will execute?
Swift
enum SampleError: Error {
    case fail
    case anotherFail
}

func testFunc() throws {
    throw SampleError.anotherFail
}

do {
    try testFunc()
} catch SampleError.fail {
    print("Caught fail")
} catch SampleError.anotherFail {
    print("Caught anotherFail")
} catch {
    print("Caught unknown error")
}
ACaught anotherFail
BCaught fail
CCaught unknown error
DNo output
Attempts:
2 left
💡 Hint
The thrown error matches the second catch pattern.
Predict Output
expert
2:00remaining
Output of nested do-try-catch blocks
What is the output of this Swift code?
Swift
enum SampleError: Error {
    case fail
}

func innerFunc() throws {
    throw SampleError.fail
}

do {
    do {
        try innerFunc()
    } catch {
        print("Inner catch")
        throw error
    }
} catch {
    print("Outer catch")
}
AInner catch
BOuter catch
CInner catch\nOuter catch
DNo output
Attempts:
2 left
💡 Hint
The inner catch rethrows the error, which is caught by the outer catch.