What if your program could try risky actions without crashing, catching problems like a safety net?
Why Do-try-catch execution flow in Swift? - Purpose & Use Cases
Imagine you are writing a program that reads a file from your computer. Without special handling, if the file is missing or unreadable, your program just crashes or stops working unexpectedly.
Manually checking every possible error before doing an action is slow and messy. You might forget some checks, causing your program to crash or behave strangely. It's like walking blindfolded, hoping not to trip.
Using do-try-catch lets you try risky actions safely. If something goes wrong, you catch the error and decide what to do next, keeping your program running smoothly without crashes.
let file = openFile("data.txt") if file == nil { print("Error: File not found") } else { readFile(file!) }
do {
let file = try openFile("data.txt")
readFile(file)
} catch {
print("Error reading file: \(error)")
}It enables your program to handle errors gracefully and keep working, just like having a safety net when trying something risky.
Think about a banking app that tries to transfer money. If something goes wrong, like no internet or wrong account, do-try-catch helps the app show a friendly message instead of crashing.
Manual error checks are slow and easy to forget.
Do-try-catch handles errors cleanly and safely.
It keeps programs running smoothly even when things go wrong.
Practice
do-try-catch in Swift?Solution
Step 1: Understand the role of
This structure is used to run code that might throw errors and handle those errors gracefully.do-try-catchStep 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 AQuick Check:
Error handling = A [OK]
- Confusing error handling with loops
- Thinking try-catch defines functions
- Assuming it declares variables
do-try-catch block in Swift?Solution
Step 1: Recall correct
The correct syntax starts withdo-try-catchsyntaxdo {}, inside whichtryis used before the function that might throw.Step 2: Match syntax with options
do { try someFunction() } catch { handleError() } correctly placesdoblock, usestryinside, and follows withcatchblock.Final Answer:
do { try someFunction() } catch { handleError() } -> Option DQuick Check:
Correct syntax = D [OK]
- Placing try outside do block
- Swapping catch and do blocks
- Missing curly braces
enum MyError: Error { case fail }
func risky() throws {
throw MyError.fail
}
do {
try risky()
print("Success")
} catch {
print("Caught an error")
}Solution
Step 1: Analyze the function
This function always throws an error of typerisky()MyError.fail.Step 2: Trace the
Whendo-try-catchblocktry risky()runs, it throws an error, so the code jumps to thecatchblock and prints "Caught an error".Final Answer:
Caught an error -> Option BQuick Check:
Error thrown = catch block runs = B [OK]
- Assuming code after try runs despite error
- Thinking no output occurs
- Confusing compile error with runtime error
do {
try someFunction()
} catch error {
print("Error: \(error)")
}
func someFunction() {
print("Running")
}Solution
Step 1: Check function declaration
The functionsomeFunction()is called withtry, so it must be declared withthrowsto indicate it can throw errors.Step 2: Identify mismatch causing error
SincesomeFunction()is not markedthrows, the compiler will raise an error.Final Answer:
Function someFunction() must be marked with throws -> Option AQuick Check:
try requires throws function = C [OK]
- Ignoring throws keyword on function
- Thinking catch syntax is wrong
- Assuming print inside catch is invalid
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")
}Solution
Step 1: Analyze the function call
CallingreadFile("bad.txt")throwsFileError.unreadable.Step 2: Check catch blocks for matching error
The first catch handlesFileError.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 CQuick Check:
Specific catch misses, general catch runs = A [OK]
- Assuming first catch runs for all errors
- Thinking no output occurs
- Confusing error types
Ready to prove it?
Pass the test and this pattern moves unknown
