Tuesday, January 6, 2009

Abstracting Away From Exceptions

Michael Feathers:

Exceptions seem to encourage “controlled abort” as an error handling policy. You throw an exception, it travels up the stack, and you catch it someplace else. All of your work is unwound (you hope) and then you are left with the task of logging the error or trying something else.

The comments are interesting, too.

I think exceptions are especially bad in Cocoa as a way of handling expected errors. Catching them is verbose, so the natural tendency is to do so as little as possible. Secondly, methods don’t declare whether they raise exceptions, so there’s no easy way to make sure you’re catching all the ones you should. NSError, ugly though it is, actually seems to be a pretty good system for managing and propagating errors generated by different layers of code and even different languages.

Update (2009-01-16): An interesting post from Mark Wooding about Lisp conditions vs. exceptions.

4 Comments RSS · Twitter

I've always kind of preferred exceptions, but the mix of Exceptions and NSError that exists in Cocoa today needs to go. In Core Data for example, even (somewhat) common error situations can cause an exception to be raised, even though the method itself takes an NSError object as a parameter.

I don’t recall running into that problem. Do you have an example? I like the Cocoa convention that exceptions are for compile-time programmer errors and NSError is for expected runtime errors that need to be handled. If you’re commonly getting exceptions, that would seem to be either a bug in your code or in Core Data.

You should see it if you find your Core Data XML file in Finder, and enable 'Locked' in the Get Info pane. I forget exactly what method it is, but one of the Core Data objects throws an exception that comes from the underlying NSData object.

Have you filed a bug?

Leave a Comment