do/catch & defining errors (enums)
Define error enums, throw them from functions, and handle failures with do/catch patterns (specific cases, catch let, generic catch).
do/catch & defining errors (enums) is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Overview
This lesson focuses on defining typed errors and handling them with do/catch. You'll throw an enum and catch specific cases for clear recovery paths.
Error enum
Define a custom enum that conforms to Error. Associated values add helpful context.
enum FileError: Error {
case notFound(path: String)
case unreadable(path: String)
case corrupted
}
print("Defined FileError enum")Throwing basics
Mark functions that can fail with throws. Throw specific cases when preconditions are not met.
func loadText(from path: String) throws -> String {
if path.isEmpty { throw FileError.notFound(path: "(empty)") }
if !path.hasSuffix(".txt") { throw FileError.unreadable(path: path) }
return "Contents of " + path
}
print("Ready to throw on bad input")Specific catches
Use do/try/catch. Place specific catch cases first, then a general catch for the rest.
do {
let text = try loadText(from: "notes.txt")
print(text)
} catch FileError.notFound(let p) {
print("Missing file at:", p)
} catch FileError.unreadable(let p) {
print("Cannot read:", p)
} catch {
print("Other error:", error)
}catch let & switch
Use catch let error as YourError and then switch to format user-friendly messages.
do {
_ = try loadText(from: "")
} catch let error as FileError {
switch error {
case .notFound(let p): print("not found:", p)
case .unreadable(let p): print("unreadable:", p)
case .corrupted: print("file corrupted")
}
} catch {
print("unexpected:", error.localizedDescription)
}Recover vs rethrow
Decide to recover (return a fallback) or rethrow to the caller. Keep rules simple and predictable.
func mustLoad(_ path: String) throws -> String {
do {
return try loadText(from: path)
} catch FileError.notFound {
// simple recovery: default content
return "New file template"
} catch {
// escalate unknown issues
throw error
}
}
print(try? mustLoad("report.txt") ?? "(nil)")Custom errors pattern
Quick check: What is the idiomatic way to define custom errors?
Recap
Recap: Define typed errors with an Error-conforming enum, throw precise cases, and handle them via do/catch with specific branches first, generic last.
Frequently asked questions
Is the “do/catch & defining errors (enums)” lesson free?
Yes — the full text of “do/catch & defining errors (enums)” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “do/catch & defining errors (enums)”?
Define error enums, throw them from functions, and handle failures with do/catch patterns (specific cases, catch let, generic catch). You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “do/catch & defining errors (enums)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Optional chaining & error handling basics
- do/catch & defining errors (enums)
- Result types — Result