IntermediateLesson 11 of 16
Error Handling – Swift
throws, try, do/catch, Result, and defer.
Errors in Swift are perfectly ordinary values that conform to the Error protocol, usually an enum. Functions that can fail are marked with throws; the caller must confirm with try that they have noticed this.
enum KontoFehler: Error {
case zuWenig(saldo: Int, betrag: Int)
case gesperrt
}
func abheben(saldo: Int, betrag: Int) throws -> Int {
guard betrag <= saldo else {
throw KontoFehler.zuWenig(saldo: saldo, betrag: betrag)
}
return saldo - betrag
}
do {
let neu = try abheben(saldo: 100, betrag: 30)
print(neu) // 70
_ = try abheben(saldo: 50, betrag: 100)
print("not reached")
} catch KontoFehler.zuWenig(let s, let b) {
print("Balance \(s) is not enough for \(b)") // Balance 50 is not enough for 100
} catch {
print("Other error: \(error)")
}Three variants of try: try (normal, in do/catch or in a throws function), try? (returns nil on error), and try! (crash on error, only if it is impossible). defer runs when the block is left, no matter how, which is ideal for cleanup.
let unmoeglich = try? abheben(saldo: 10, betrag: 20)
print(unmoeglich == nil) // true
func verarbeite() throws {
print("opening resource")
defer { print("closing resource") } // always runs on exit
_ = try abheben(saldo: 0, betrag: 1)
print("not reached")
}
try? verarbeite()
// opening resource
// closing resourceResult<Success, Failure> stores success or failure as a value, which is useful for callbacks and for passing results along. For readable error messages, you implement LocalizedError.
import Foundation
enum LadeFehler: LocalizedError {
case nichtGefunden(String)
var errorDescription: String? {
switch self {
case .nichtGefunden(let name): return "\(name) was not found"
}
}
}
print(LadeFehler.nichtGefunden("x.txt").localizedDescription) // x.txt was not found
let r: Result<Int, KontoFehler> = .failure(.gesperrt)
switch r {
case .success(let v): print(v)
case .failure(let e): print("Error: \(e)") // Error: gesperrt
}
let n = try Result { try abheben(saldo: 50, betrag: 20) }.get()
print(n) // 30TipMany Foundation functions throw errors (reading files, decoding JSON, networking). Since Swift 6 there are also typed errors:
func f() throws(KontoFehler) specifies the exact error type.Warning
Int("abc") does not throw but returns nil. Swift initializers that can fail are usually failable (init?), not throws. Which form an API uses is stated in its signature.