Error Handling
Saving a hike can fail: the disk is full, the name is empty, or the file is corrupted. An app that pretends nothing can go wrong shows a blank screen or loses data. Swift makes failure part of a function's signature, so callers cannot forget it.
The rule
throwswarns,trymarks the risk,catchhandles the fall.
Errors in Swift are values of any type that conforms to the Error protocol — usually an enum:
enum SaveError: Error {
case emptyName
case diskFull
}A function that can fail is marked throws, and uses throw to fail:
func save(_ hike: Hike) throws {
guard !hike.name.isEmpty else { throw SaveError.emptyName }
// ... write to disk, which may also throw
}A caller must mark each throwing call with try, and handle errors in a do–catch:
do {
try save(hike)
showSavedBanner()
} catch SaveError.emptyName {
showMessage("Give your hike a name.")
} catch {
showMessage("Could not save: \(error.localizedDescription)")
}When the first try fails, the rest of the do block is skipped and the matching catch runs. The last plain catch catches anything else and gives you an implicit error constant.
Two shortcuts change a throwing call into something else:
try?turns the result into an optional:nilif it threw. Use it when failure just means "no value".try!asserts it will never throw, and crashes if it does. Rarely appropriate.
A function can also rethrow by simply being throws itself and writing try without a do — the error passes up to its caller.