Error Handling
Error handling allows your program to safely respond to and recover from unexpected failures.
Representing Errors
In Swift, errors are represented using types that conform to the Error protocol. Enums are the most common and effective way to group related error conditions.
swift
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}Throwing Errors
Use the throws keyword in a function's declaration to indicate it can throw an error.
swift
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Broken" {
throw PrinterError.onFire
}
return "Job sent"
}Handling Errors (do-catch)
Wrap your throwing functions inside a do block and use the try keyword to call them. You can then handle specific failures in the following catch blocks.
swift
do {
let response = try send(job: 10, toPrinter: "Broken")
print(response)
} catch PrinterError.onFire {
print("Call the fire department!")
} catch {
print("Error: \(error)")
}Optional Errors (try?)
Use try? to handle an error by converting it to an optional value. If an error is thrown, the result is nil.
swift
let response = try? send(job: 10, toPrinter: "Broken")
// response is nilDisabling Error Propagation (try!)
Use try! if you are absolutely certain a function will not throw an error at runtime. If it does throw, your app will immediately crash.
swift
let response = try! send(job: 10, toPrinter: "Office")