Bird
Raised Fist0
Swiftprogramming~20 mins

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

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

Practice

(1/5)
1. What is the main purpose of using do-try-catch in Swift?
easy
A. To handle errors safely without crashing the program
B. To create loops that run multiple times
C. To define new functions
D. To declare variables with default values

Solution

  1. Step 1: Understand the role of do-try-catch

    This structure is used to run code that might throw errors and handle those errors gracefully.
  2. Step 2: Identify the purpose

    It prevents the program from crashing by catching errors and allowing alternative actions.
  3. Final Answer:

    To handle errors safely without crashing the program -> Option A
  4. Quick Check:

    Error handling = A [OK]
Hint: Remember: try means risky code, catch means safe backup [OK]
Common Mistakes:
  • Confusing error handling with loops
  • Thinking try-catch defines functions
  • Assuming it declares variables
2. Which of the following is the correct syntax to start a do-try-catch block in Swift?
easy
A. try someFunction() do { catch handleError() }
B. try { do someFunction() } catch { handleError() }
C. catch { try someFunction() } do { handleError() }
D. do { try someFunction() } catch { handleError() }

Solution

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

    The correct syntax starts with do {}, inside which try is used before the function that might throw.
  2. Step 2: Match syntax with options

    do { try someFunction() } catch { handleError() } correctly places do block, uses try inside, and follows with catch block.
  3. Final Answer:

    do { try someFunction() } catch { handleError() } -> Option D
  4. Quick Check:

    Correct syntax = D [OK]
Hint: Remember: do { try ... } catch { ... } is the pattern [OK]
Common Mistakes:
  • Placing try outside do block
  • Swapping catch and do blocks
  • Missing curly braces
3. What will be the output of the following Swift code?
enum MyError: Error { case fail }

func risky() throws {
  throw MyError.fail
}

do {
  try risky()
  print("Success")
} catch {
  print("Caught an error")
}
medium
A. Success
B. Caught an error
C. No output
D. Compile-time error

Solution

  1. Step 1: Analyze the function risky()

    This function always throws an error of type MyError.fail.
  2. Step 2: Trace the do-try-catch block

    When try risky() runs, it throws an error, so the code jumps to the catch block and prints "Caught an error".
  3. Final Answer:

    Caught an error -> Option B
  4. Quick Check:

    Error thrown = catch block runs = B [OK]
Hint: If try throws, catch block runs, not code after try [OK]
Common Mistakes:
  • Assuming code after try runs despite error
  • Thinking no output occurs
  • Confusing compile error with runtime error
4. Identify the error in this Swift code snippet:
do {
  try someFunction()
} catch error {
  print("Error: \(error)")
}

func someFunction() {
  print("Running")
}
medium
A. Function someFunction() must be marked with throws
B. Catch block syntax is incorrect
C. Missing do keyword
D. Print statement inside catch is invalid

Solution

  1. Step 1: Check function declaration

    The function someFunction() is called with try, so it must be declared with throws to indicate it can throw errors.
  2. Step 2: Identify mismatch causing error

    Since someFunction() is not marked throws, the compiler will raise an error.
  3. Final Answer:

    Function someFunction() must be marked with throws -> Option A
  4. Quick Check:

    try requires throws function = C [OK]
Hint: Only functions marked throws can be called with try [OK]
Common Mistakes:
  • Ignoring throws keyword on function
  • Thinking catch syntax is wrong
  • Assuming print inside catch is invalid
5. Given this Swift code, what will be printed?
enum FileError: Error { case notFound, unreadable }

func readFile(_ name: String) throws -> String {
  if name == "missing.txt" { throw FileError.notFound }
  if name == "bad.txt" { throw FileError.unreadable }
  return "File content"
}

do {
  let content = try readFile("bad.txt")
  print(content)
} catch FileError.notFound {
  print("File not found")
} catch {
  print("Other error")
}
hard
A. File content
B. File not found
C. Other error
D. No output

Solution

  1. Step 1: Analyze the function call

    Calling readFile("bad.txt") throws FileError.unreadable.
  2. Step 2: Check catch blocks for matching error

    The first catch handles FileError.notFound, which does not match. The second catch is a general catch that handles all other errors, so it runs and prints "Other error".
  3. Final Answer:

    Other error -> Option C
  4. Quick Check:

    Specific catch misses, general catch runs = A [OK]
Hint: Specific catch runs only if error matches exactly [OK]
Common Mistakes:
  • Assuming first catch runs for all errors
  • Thinking no output occurs
  • Confusing error types
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