views:

445

answers:

1

A few weeks ago I started using Core Data for the first time in a non-trivial application. One of the things that surprised and confused me was how error handling works. To give an example, one of the first things I tried was setting my data file as "locked" in Finder, to order to make sure I was properly handling the NSError object returned by reference when I set the file URL. To my surprise, instead of returning nil and setting the NSError, the persistent store coordinator raised an uncaught exception from the underlying NSData!

At the same time, it seems like error handling is a bit unnecessary sometimes in Core Data. For instance, I don't see any obvious reason why a fetch request would need error handling beyond programmer mistakes (which, incidentally, also raise an exception in my experience). In these cases, I've been passing NULL for the NSError reference pointer.

Between try / catch blocks and NSError I could spend a lot of time writing code to appease Core Data, but I want to be practical about it so I'm not spending time on error code that will never run. With that in mind, how do you approach error handling in your applications? What errors have you seen in the real world that you should make sure to account for?

+2  A: 

The error handling direction that Apple has been taking since 1.4 has been NSError for errors that the application should know about (like the one you stated above) and exceptions for programming errors (that should never get past QA).

In general, you should program with these guidelines in mind. When you find an issue like this, you can program a handler for now based on the actual results you are finding, but you should also post a bug report to Apple right away since this pattern is contrary to the one they're adopting.

You can post the bug report to http://bugreport.apple.com/. You will need an ADC account but you can post bug reports with the free account. I've found them to be extremely responsive to bugs in the development toolkit and issues like this, where the framework behaves contradictory to their stated design patterns.

Jason Coco
That's good advice, but I was really hoping for some more practical advice on which errors I'm most likely to run into with a real-world Core Data application.
Marc Charbonneau