Swift: if a do return try fails does catch execute

return, swift

Solution

What you have should work as expected. Basically what happens is if a throw occurs at any time within a do, the catch is called and any code after the throw will not be executed.

Problem

I am working on a piece of code that is going to fetch an array of `NSManagedObject`s from CoreData. When using a do catch statement in my code it doesn't seem right to do it this way, but it is the simplest way I can write this line of code. In any other scenario when you use the `return` statement you are jumping out of the current function you are in. And you can be assured that no other code in your function will execute past the `return` statement. I am wondering if the same applies to Swift's `do catch` paradigm. ``` class func getAll() -> [MMNotification] { let context = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<MMNotification>(entityName: "MMNotification") do { return try context.fetch(fetchRequest) } catch { // Will this 'catch' if the try fails, // even if we said we are 'return'ing right before the 'try'? return [] } } ``` Here I am fetching a list of notifications stored in CoreData. In the `do` block you can see the line of code in question. QUESTION Will the `catch` block execute if the `try` fails after already stating that the function should `return`?

Original source