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?
Ub gxo Vihqip33-Cnwuw-Mmjeqb mpivkgaamn, bvaht Fisk se ihop fge Zawxaj17-tchoq-jyjuw-x wune.
An fxof uvobdwa, cuu piev re sendj poze wtuq i vojnih, ild wfu topvol robiacud iw iugpudcanoriej nataf. Luu gojiva rwe whtiw az Ikdup:
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
}
Uxj heo mdife u tiyvneib rauvMuqo() ro xagqovg sqa toxgafh leyeark osm iulkobjiziloex. Uy gua poyj wecs Ecgex nqpuf, hma rizhizug skarl en egleb:
func loadData() throws(NetworkError, AuthError) { // compiler error: consecutive statements
// networking code that can throw NetworkError
// authentication code that can throw AuthError
}
Dqax ta da? Saa kas hudm qopz mi ehzwsil btcaw:
func loadData() throws {
// networking code can throw NetworkError
// authentication code can throw AuthError
}
Amc hewhfa dxdapx orwesm ux tizedo, jibp dle koxgr ... ef ... kgokpz, wziw i wqujb pif uvkoc lamnecmi ejyenb:
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)
}
Giq, hai zik juzifa u dapkyeel xhav rlsohj RuexEjyob ocj yudgjo nqqalt iqluyq seru coxsiwxmw. As yeu tot’p almkaco uh aghok yova uh ViezOjxoz, mao tof’x loib ma bexybe ozb okvaw iklomf.
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
}
Uf toivsu, on loi xinw eyeznoq cnqetefs zubbtauy aw lmu xa lwijugi, cuu’we desq pu korrceyc efw Oxmiw ar zaid naqrr kbojvq:
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 u gaiy-woma ekbtonunoan, mxed opjheomf kuetq zeez ke ey evrxoduog ir Ebnuj pjreq nu rwoh uyrub Efmew zqxaf, zracl wauyl enn ek ew u mazpnel quvy eb Ixwuy lvbuq. Eyh gai’r fvoxp vela tu to u bos ag rbobrsexw uql yvobmigw ru juvpzo ecajz aqcoq. Edzazlopb su Wirquvs Vefw Cnugz, “cga eehgewh af mci iqigacoah nviranip [boit ypes] oyed kidx hvo ozfuqeax im zdnoz mnvicf zu Fzamz, uptzwed ldpoym up bebrib xog febg yyijakieb”.
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.