Error handling not working as expected

I created a simple core data project and added a function that would fetch records of an entity named "Task"

I purposley gave a wrong name for the Entity's field so it would throw an error. I would expect that the error would be "caught" by the exaustive catch as you can see below.

Actually the executeFetchRequest method does fail and I get an error print-out at the console output, but the catch closure is not getting called.


Here is the code:


        let request = NSFetchRequest(entityName: "Task")
        let predicate = NSPredicate(format: "priasdfority_ == %i", 1)
        request.predicate = predicate
       
        do{
            let results = try self.managedObjectContext.executeFetchRequest(request)
            print(results)
        }catch{
            print("There was an error")
            print(error)
        }


Is there something wrong with the code, or am I failing to grasp how the new error handling works ?

As far as I can see, there is nothing wrong with your code. NSFetchRequest resolveEntityWithContext: (called by NSManagedObjectContext executeFetchRequest:error:) throws an Objective-C exception instead of making executeFetchRequest:error: return nil. You cannot catch Objective-C exceptions in Swift, so there is nothing you can do (except file a bug report).

Accepted Answer

What you may not grasp is that Cocoa's traditional error handling rules are still in effect:

  • If a method fails and there's only really one failure case for it (trying to convert a non-numeric string to a number, etc.), the method returns nil or false.
  • If an operation fails because of some complex issue with the current state of the computer (no such file, Wi-Fi turned off, etc.), the method emits an NSError. In Swift, NSErrors are handled with the do/try/catch mechanism.
  • If an operation fails because the programmer wrote code that did something invalid (out-of-range array index, etc.), the method fails an assertion or raises an exception, which you should generally allow to crash your app. In Swift, it's not possible to catch exceptions.

Creating a fetch request with an inaccurate entity name falls into that third category: failures that can only be the result of programmer error. Such problems are still handled by failing an assertion and crashing your app.

Error handling not working as expected
 
 
Q