📖 Scenario: Imagine you are writing a simple Swift program that reads a number from a string and handles errors if the string is not a valid number.
🎯 Goal: You will build a Swift program that uses do-try-catch to safely convert a string to a number and handle possible errors.
📋 What You'll Learn
Create a function that throws an error if the string is not a valid number
Use a do block with try to call the function
Add catch blocks to handle errors
Print the result or error message
💡 Why This Matters
🌍 Real World
Handling errors when converting user input or data from files is very common in apps and programs.
💼 Career
Understanding <code>do-try-catch</code> is essential for Swift developers to write robust and crash-free code.
Progress0 / 4 steps
1
Create a throwing function
Write a function called convertToInt that takes a String parameter named input and returns an Int. The function should throw an error of type ConversionError.invalidNumber if the string cannot be converted to an integer. Define the ConversionError enum with a case invalidNumber.
Swift
Hint
Use guard let to try converting the string to Int. If it fails, throw the error.
2
Set up the input string
Create a constant called inputString and set it to the string "123a".
Swift
Hint
Use let inputString = "123a" to create the string.
3
Use do-try-catch to convert the string
Write a do block that tries to convert inputString to an integer using try convertToInt(input: inputString). Store the result in a constant called number. Add a catch block that catches ConversionError.invalidNumber and prints "Invalid number format.". Add a general catch block that prints "Unknown error.".
Swift
Hint
Use do { let number = try convertToInt(input: inputString) } and add catch blocks for errors.
4
Print the final output
Run the program and observe the output printed by the do-try-catch block.
Swift
Hint
The program should print Invalid number format. because the string contains a letter.
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
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.
Step 2: Identify the purpose
It prevents the program from crashing by catching errors and allowing alternative actions.
Final Answer:
To handle errors safely without crashing the program -> Option A
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
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.
Step 2: Match syntax with options
do { try someFunction() } catch { handleError() } correctly places do block, uses try inside, and follows with catch block.
Final Answer:
do { try someFunction() } catch { handleError() } -> Option D
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
Step 1: Analyze the function risky()
This function always throws an error of type MyError.fail.
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".
Final Answer:
Caught an error -> Option B
Quick Check:
Error thrown = catch block runs = B [OK]
Hint: If try throws, catch block runs, not code after try [OK]
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".
Final Answer:
Other error -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.