Coding/Learn/swift/swift error handling and do catch
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnError Handling: Throwing Functions, Do-Catch & Try Options
13 / 20 0%
Lesson 13 of 20
9 mins read

Error Handling: Throwing Functions, Do-Catch & Try Options

PreviousNext Lesson
In Plain English

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!).

The Mental Model

"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.

PointCore Rules to Remember

Point star
Explicit Propagation: Every point where an error can be thrown is clearly marked with try at the call site.
Point star
Pattern Matching Catch: catch AuthError.invalidPassword handles specific domain error cases directly.
Point star
Implicit error Variable: catch blocks without explicit variable names automatically bind the thrown error to error.

Common Beginner Traps & How to Fix Them

Mistake: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?.

Pro Tip: Use try? when you only care whether an operation succeeded or failed and don't need the specific error details.

Live Interactive Example

Hit Run Code to see it live
Custom Error Handling with Do-Catch and try?
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Output Console
Click "Run Code" to view the rendered output.
How it works: The 100 withdrawal threw insufficientFunds caught by the specific catch block, and 10 succeeded with try?.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Safe Division Error Handling

  • PointDefine an enum MathError: Error with case .divisionByZero.
  • PointWrite a function divide(_ a: Double, _ b: Double) throws -> Double.
  • PointIf b == 0, throw MathError.divisionByZero. Otherwise return a / b.
  • PointIn top-level code, call divide(10.0, 0.0) inside a do-catch block and print "Caught error: Division by zero".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates