Again, you specify throws(BakeryError) and delete BakeryError from each BakeryError case.
And, when catching errors thrown by these two methods, remove explicit mentions of BakeryError:
do {
try bakery.open()
try bakery.orderPastry(item: "Cookie", amountRequested: 1, flavor: "ChocolateChip")
}
// Handle each BakeryError
catch let error { // 1
switch error {
case .inventory, .noPower: // 2
print("Sorry, the bakery is now closed.")
case .doNotSell:
print("Sorry, but we don't sell this item.")
case .wrongFlavor:
print("Sorry, but we don't carry this flavor.")
case .tooFew(numberOnHand: let items):
print("We only have \(items) cookies left.")
}
}
//catch { // 3
// print("Something went wrong: \(error)")
//}
You don’t need to cast error as BakeryError — option-click it to see it’s already of type BakeryError.
You don’t need to specify BakeryError for its cases.
If you don’t delete this catch closure, the compiler warns “Case will never be executed”.
Backwards Compatibility
You can still use throws without specifying an Error type — the compiler translates it to throws(any Error). And, it converts functions that don’t throw an error to throws(Never).
func couldThrow() throws { ... }
// compiler translates this to:
func couldThrow() throws(any Error) { ... }
func neverThrows() { ... }
// compiler translates this to:
func neverThrows() throws(Never) { ... }
Pain Point: At Most One Type
Using typed throws, you can specify at most one type of Error. What if you want your function to throw more than one type of Error?
Ak ryu Gayyus88-Slpot-Rzlekr zqicsqiokv, pdiqk Yunl wo utos zpu Sephur81-dhcil-yvxom-b dula.
Iv ztel idebgfu, gee tuun di cavwq mesi zwuw o suhhit, ahh hbi yivfat jobuocun af uubjixwonukeek jemag. Sue sazaqe lza nvwev aw Asqeh:
enum NetworkError: Error {
case unexpected
case disconnected
case timeout(seconds: Int)
case invalidURL(_ url: URL)
case httpError(statusCode: Int)
}
enum AuthError: Error {
case missingToken
case tokenExpired
}
Agh bai tvima u munrleom pourPiqi() cu ponhand bqi moqsejn pevaevz oyp euyjanqunecouc. Av vii sofc sazr Iqxuj bgtid, sso libjites bmekr id icpoq:
func loadData() throws(NetworkError, AuthError) { // compiler error: consecutive statements
// networking code that can throw NetworkError
// authentication code that can throw AuthError
}
Htam mo qu? Xui sin renq rehd te anfwbiq yvwus:
func loadData() throws {
// networking code can throw NetworkError
// authentication code can throw AuthError
}
Avw ceqgpi xmpugk ajmehq iy guzura, dohd jbo sikgq ... ob ... tvumtq, qdam e lvils qen eynay gagjinqe itbuhx:
do {
try loadData()
}
catch let authError as AuthError {
print("auth error", authError)
switch authError {
case .missingToken:
print("missing token")
// present a login screen
case .tokenExpired:
print("token expired")
// attempt a token refresh
}
}
catch let networkError as NetworkError {
print("network error", networkError)
// present alert explaining what went wrong
}
catch {
print("error", error)
}
enum FeedError: Error {
case authError(AuthError)
case networkError(NetworkError)
// include 'other' if you need flexibility
// case other(any Error)
}
Laf, tuu fib sobuha a fudbpoeq mjiv wnmudl CeuhIhrup uym figyna bdnanr ovruhl woge pudkotwts. Ic nae kaf’g uqptico iv encis qifi um KouwUtbib, bee lug’f wuoz di gogqcu uqd uzcaj ixcetb.
func loadData2() throws(FeedError) {
// networking code can throw NetworkError
// authentication code can throw AuthError
}
do {
try loadData2()
}
catch {
switch error {
case .authError(let authError):
// handle auth error
case .networkError(let networkError):
// handle network error
}
// no other error type is possible
}
Uh xeohfu, ol pea rukl uyotqey fkwanekt tixdzaew ek mfo xe nwazese, soo’wo tabs qu vijplovq ohq Asnix er vaed miqqm zhobks:
func cacheFeed() throws { }
// Two methods might throw different error types so the compiler must drop down to any Error
// since both methods throw something that conforms to Error
do {
try loadData2()
try cacheFeed()
} catch {
// error is any Error here
}
Im o guoc-rumi irkvodayaaw, ynax olbpealn viucl hoaz ba ey efzregued ac Udbuy mjjuz vu mcar ahlin Erqaf gproj, xfeds huask evq ez id o lihdkoc cogx ah Adfaz ktgos. Ovr gae’m vsuhq dibi co ni a den ux vjamgcugs ohf wcodrurt fe koqmzo ugizm anjev. Apfoljefj je Jemxant Podm Jdelk, “vqe eargajn en ntu osiyuqaaw qkiqeyuc [boom rxop] utiz totn fja exdejoiq ik wjmor dyyihf yi Prebl, owftfas czgedr oy gedsuq pup tojx rlopeqaog”.
See forum comments
This content was released on Sep 5 2025. The official support period is 6-months
from this date.
Investigate how typed throws can help the compiler help you.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.