Challenge - 5 Problems
Swift Do-Try-Catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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") }
Attempts:
2 left
💡 Hint
The function does not throw an error, so the catch block is skipped.
✗ Incorrect
Since testFunc() returns "Success" without throwing, the try succeeds and prints "Success".
❓ Predict Output
intermediate2: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") }
Attempts:
2 left
💡 Hint
The function throws an error, so the catch block runs.
✗ Incorrect
Since testFunc() throws SampleError.fail, the try fails and the catch block prints "Error caught".
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
In Swift, 'try' must be inside a do-catch or handled with try? or try! outside.
✗ Incorrect
Using 'try' outside a do-catch without try? or try! causes a compile-time error.
🧠 Conceptual
advanced2: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") }
Attempts:
2 left
💡 Hint
The thrown error matches the second catch pattern.
✗ Incorrect
The thrown error is SampleError.anotherFail, so the matching catch block prints "Caught anotherFail".
❓ Predict Output
expert2: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") }
Attempts:
2 left
💡 Hint
The inner catch rethrows the error, which is caught by the outer catch.
✗ Incorrect
The inner do-catch catches the error and prints "Inner catch", then rethrows it. The outer catch catches it and prints "Outer catch".