Error Handling

In Swift, methods that throw errors will have the keyword throws on the end of them.

func save() throws  

We must put calls to functions like this in a do { } block and use the keyword try to call them.

do {  
    try context.save()
} catch let error {
    // error will be something that implements the Error protocol, e.g., NSError
    // usually these are enums that have associated values to get error details 
   throw error // this would re-throw the error (only ok if the method we are in throws)
}

If we are certain a call will not throw an error, we can force try it with try! try! context.save. This will crash the program if save() actually throws an error.

On the other hand we can conditionally try, turning the return into a Optional (which will be nil if it fails) let x = try? errorProneFunctionThatReturnsAnInt() (in this case x will be Int?).