Python Error Handling: Throwing Functions, Do-Catch & Try Options
Swift uses explicit error propagation. Learn the Error protocol, throwing functions (throws), throwing errors (throw), capturing errors with do...catch, converting errors to optionals (try?), and disabling error propagation (try!).
"A throwing function is like a vending machine with a coin return slot: if you request an item that is sold out (throw), the transaction halts and the machine ejects an explicit error token into your hands (catch)."
Deep Dive: How It Works
The Error Protocol: Types represent errors by conforming to the empty Error protocol (typically an enum).
Throwing Functions: func perform() throws -> Result marks a function that can propagate errors.
The try Keyword: Must prefix every call to a throwing function.
try?: Converts throwing calls into Optionals (returns nil on error, unwrapped value on success).
try!: Asserts that an error will never happen; crashes on error.
do...catch Blocks: Captures errors and provides an implicit error variable inside the catch block.
Syntax Blueprint
enum AuthError: Error { case invalidPassword }
do {
try authenticate()
} catch {
print("Caught: \(error)")
}Throw errors with throw, call with try inside do blocks, and handle failures in catch.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Calling a throwing function without writing try (e.g. let res = loadData()).Why it happens: Swift compiler requires explicit try, try?, or try! on all throwing calls.
How to fix: Prefix call with try inside a do-catch block, or use try?.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Safe Division Error Handling
Define an enum MathError: Error with case .divisionByZero.
Write a function divide(_ a: Double, _ b: Double) throws -> Double.
If b == 0, throw MathError.divisionByZero. Otherwise return a / b.
In top-level code, call divide(10.0, 0.0) inside a do-catch block and print "Caught error: Division by zero".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.