What if your app could catch mistakes before they cause crashes and keep users happy?
Why Error handling (try, catch, throw) in iOS Swift? - Purpose & Use Cases
Imagine you are building an app that downloads photos from the internet. Without error handling, if the internet is slow or the photo link is broken, your app might just crash or freeze without telling the user what went wrong.
Manually checking every step for problems is slow and easy to forget. If you miss a check, your app can crash unexpectedly. It's like walking blindfolded on a rocky path -- you might trip and fall without warning.
Using try, catch, throw lets your app safely test risky actions and gracefully handle problems. It's like having a safety net that catches errors and lets you decide how to respond, keeping your app smooth and user-friendly.
let data = downloadPhoto(url)
// What if download fails? No clear way to handle itdo {
let data = try downloadPhoto(url)
} catch {
print("Oops, something went wrong!")
}This lets your app stay strong and responsive, even when unexpected problems happen behind the scenes.
Think about a banking app: if a transfer fails, error handling lets the app show a clear message instead of freezing or losing your money.
Error handling prevents app crashes by managing unexpected problems.
Try, catch, and throw let you test risky code and respond safely.
This makes apps more reliable and user-friendly.
Practice
try keyword do in Swift error handling?Solution
Step 1: Understand the role of
Thetrytrykeyword is used before calling a function that can throw an error, signaling that error handling is needed.Step 2: Differentiate from other keywords
catchhandles errors,throwraises errors, and defining errors usesenumorstruct.Final Answer:
It calls a function that might throw an error and requires handling. -> Option BQuick Check:
trycalls throwing functions [OK]
- Confusing try with catch or throw keywords
- Thinking try itself catches errors
- Using try without a throwing function
Solution
Step 1: Recall the correct do-catch syntax
In Swift, error handling usesdo { try ... } catch { ... }blocks to catch errors.Step 2: Identify the correct option
do { try someFunction() } catch { print("Error") } correctly wraps thetrycall inside adoblock followed by acatchblock.Final Answer:
do { try someFunction() } catch { print("Error") } -> Option AQuick Check:
do-catch syntax = do { try someFunction() } catch { print("Error") } [OK]
- Placing try outside do block
- Using catch without do
- Incorrect order of try and catch
enum FileError: Error { case notFound }
func readFile() throws {
throw FileError.notFound
}
do {
try readFile()
print("File read successfully")
} catch {
print("Failed to read file")
}Solution
Step 1: Analyze the throwing function
The functionreadFile()always throwsFileError.notFound, so it never completes normally.Step 2: Understand the do-catch behavior
Thetry readFile()call throws an error, so control jumps to thecatchblock, printing "Failed to read file".Final Answer:
Failed to read file -> Option DQuick Check:
Thrown error triggers catch block [OK]
- Assuming code after try runs if error thrown
- Thinking no output if error thrown
- Confusing error throwing with returning
func riskyFunction() throws {
throw NSError(domain: "Error", code: 1)
}
try riskyFunction()Solution
Step 1: Check error handling usage
The code calls a throwing function withtrybut does not handle errors withdo-catchor propagate withtry?ortry!.Step 2: Confirm syntax correctness
The throw statement and function declaration are correct; the problem is missing error handling around the call.Final Answer:
Missing do-catch block to handle the thrown error. -> Option AQuick Check:
Throwing calls need error handling [OK]
- Calling throwing functions without error handling
- Confusing throw syntax with try syntax
- Assuming try alone handles errors
loadData() that throws a custom error DataError.invalidFormat if data is bad. Which code correctly defines the error and throws it inside the function?Solution
Step 1: Define a custom error type conforming to Error
In Swift, custom errors are usually enums conforming to theErrorprotocol, likeenum DataError: Error.Step 2: Throw the custom error inside the function
The functionloadData()declaresthrowsand throwsDataError.invalidFormatcorrectly.Final Answer:
enum DataError: Error { case invalidFormat } func loadData() throws { throw DataError.invalidFormat } -> Option CQuick Check:
Custom errors use enum + Error protocol [OK]
- Not conforming error type to Error protocol
- Using struct or class without Error conformance
- Forgetting throws keyword in function
Ready to prove it?
Pass the test and this pattern moves unknown
