Bird
Raised Fist0
iOS Swiftmobile~20 mins

Error handling (try, catch, throw) in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Error Handling Demo
This screen lets the user enter a number and tries to convert it to an integer. If the input is invalid, it shows an error message using Swift's try, catch, and throw error handling.
Target UI
-------------------------
| Error Handling Demo   |
-------------------------
| Enter a number:       |
| [______________]     |
| [Convert]            |
|                      |
| Result:              |
|                      |
-------------------------
A TextField for user input of a number
A Convert button below the TextField
When Convert is tapped, try to convert input to Int using a throwing function
If conversion succeeds, show 'Valid number: X' in Result label
If conversion fails, catch the error and show 'Error: Invalid number' in Result label
Use Swift's try, catch, and throw keywords properly
Starter Code
iOS Swift
import SwiftUI

struct ErrorHandlingDemoView: View {
    @State private var userInput = ""
    @State private var resultMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Error Handling Demo")
                .font(.title)

            TextField("Enter a number", text: $userInput)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.numberPad)
                .padding(.horizontal)

            Button("Convert") {
                // TODO: Call the function that tries to convert input
                // and update resultMessage accordingly
            }
            .buttonStyle(.borderedProminent)

            Text("Result: \(resultMessage)")
                .padding()

            Spacer()
        }
        .padding()
    }

    // TODO: Add a throwing function to convert String to Int
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
import SwiftUI

enum ConversionError: Error {
    case invalidNumber
}

struct ErrorHandlingDemoView: View {
    @State private var userInput = ""
    @State private var resultMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Error Handling Demo")
                .font(.title)

            TextField("Enter a number", text: $userInput)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.numberPad)
                .padding(.horizontal)

            Button("Convert") {
                do {
                    let number = try convertToInt(userInput)
                    resultMessage = "Valid number: \(number)"
                } catch {
                    resultMessage = "Error: Invalid number"
                }
            }
            .buttonStyle(.borderedProminent)

            Text("Result: \(resultMessage)")
                .padding()

            Spacer()
        }
        .padding()
    }

    func convertToInt(_ input: String) throws -> Int {
        if let number = Int(input) {
            return number
        } else {
            throw ConversionError.invalidNumber
        }
    }
}

This app screen uses a TextField to get user input as a string. The convertToInt function tries to convert the string to an integer. If it fails, it throws a custom error ConversionError.invalidNumber.

When the user taps the Convert button, the app uses a do-try-catch block to call convertToInt. If conversion succeeds, it updates the result message with the valid number. If it fails, it catches the error and shows an error message.

This demonstrates how to handle errors gracefully in Swift using try, catch, and throw.

Final Result
Completed Screen
-------------------------
| Error Handling Demo   |
-------------------------
| Enter a number:       |
| [12345__________]    |
| [Convert]            |
|                      |
| Result:              |
| Valid number: 12345  |
-------------------------
User types a number in the TextField
User taps Convert button
If input is a valid number, Result label shows 'Valid number: X'
If input is invalid (e.g., letters), Result label shows 'Error: Invalid number'
Stretch Goal
Add a Clear button that resets the input and result message
💡 Hint
Add another Button below Convert that sets userInput and resultMessage to empty strings

Practice

(1/5)
1. What does the try keyword do in Swift error handling?
easy
A. It catches an error thrown by a function.
B. It calls a function that might throw an error and requires handling.
C. It defines a new error type.
D. It throws an error manually.

Solution

  1. Step 1: Understand the role of try

    The try keyword is used before calling a function that can throw an error, signaling that error handling is needed.
  2. Step 2: Differentiate from other keywords

    catch handles errors, throw raises errors, and defining errors uses enum or struct.
  3. Final Answer:

    It calls a function that might throw an error and requires handling. -> Option B
  4. Quick Check:

    try calls throwing functions [OK]
Hint: Remember: try calls, catch handles, throw creates errors [OK]
Common Mistakes:
  • Confusing try with catch or throw keywords
  • Thinking try itself catches errors
  • Using try without a throwing function
2. Which of the following is the correct syntax to catch an error in Swift?
easy
A. do { try someFunction() } catch { print("Error") }
B. try { someFunction() } catch { print("Error") }
C. catch { try someFunction() }
D. do catch { try someFunction() }

Solution

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

    In Swift, error handling uses do { try ... } catch { ... } blocks to catch errors.
  2. Step 2: Identify the correct option

    do { try someFunction() } catch { print("Error") } correctly wraps the try call inside a do block followed by a catch block.
  3. Final Answer:

    do { try someFunction() } catch { print("Error") } -> Option A
  4. Quick Check:

    do-catch syntax = do { try someFunction() } catch { print("Error") } [OK]
Hint: Remember: do { try } catch { } is the pattern [OK]
Common Mistakes:
  • Placing try outside do block
  • Using catch without do
  • Incorrect order of try and catch
3. What will be printed when running this Swift code?
enum FileError: Error { case notFound }
func readFile() throws {
  throw FileError.notFound
}
do {
  try readFile()
  print("File read successfully")
} catch {
  print("Failed to read file")
}
medium
A. Compile error
B. File read successfully
C. No output
D. Failed to read file

Solution

  1. Step 1: Analyze the throwing function

    The function readFile() always throws FileError.notFound, so it never completes normally.
  2. Step 2: Understand the do-catch behavior

    The try readFile() call throws an error, so control jumps to the catch block, printing "Failed to read file".
  3. Final Answer:

    Failed to read file -> Option D
  4. Quick Check:

    Thrown error triggers catch block [OK]
Hint: Thrown error skips try block print, runs catch print [OK]
Common Mistakes:
  • Assuming code after try runs if error thrown
  • Thinking no output if error thrown
  • Confusing error throwing with returning
4. Identify the error in this Swift code snippet:
func riskyFunction() throws {
  throw NSError(domain: "Error", code: 1)
}
try riskyFunction()
medium
A. Missing do-catch block to handle the thrown error.
B. The function cannot throw NSError type errors.
C. The throw statement syntax is incorrect.
D. try keyword is not allowed with throwing functions.

Solution

  1. Step 1: Check error handling usage

    The code calls a throwing function with try but does not handle errors with do-catch or propagate with try? or try!.
  2. Step 2: Confirm syntax correctness

    The throw statement and function declaration are correct; the problem is missing error handling around the call.
  3. Final Answer:

    Missing do-catch block to handle the thrown error. -> Option A
  4. Quick Check:

    Throwing calls need error handling [OK]
Hint: Always handle errors from throwing functions with do-catch or try? [OK]
Common Mistakes:
  • Calling throwing functions without error handling
  • Confusing throw syntax with try syntax
  • Assuming try alone handles errors
5. You want to write a function loadData() that throws a custom error DataError.invalidFormat if data is bad. Which code correctly defines the error and throws it inside the function?
hard
A. class DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
B. struct DataError { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
C. enum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }
D. enum DataError { case invalidFormat } func loadData() throws { throw DataError.invalidFormat }

Solution

  1. Step 1: Define a custom error type conforming to Error

    In Swift, custom errors are usually enums conforming to the Error protocol, like enum DataError: Error.
  2. Step 2: Throw the custom error inside the function

    The function loadData() declares throws and throws DataError.invalidFormat correctly.
  3. Final Answer:

    enum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat } -> Option C
  4. Quick Check:

    Custom errors use enum + Error protocol [OK]
Hint: Use enum conforming to Error for custom errors [OK]
Common Mistakes:
  • Not conforming error type to Error protocol
  • Using struct or class without Error conformance
  • Forgetting throws keyword in function
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