Consider the following Cocoa/Obj-C code snippets:
MyClass *obj; @try { [obj doSomething]; } @catch (NSException * e) { NSLog(@'Exception occurred: %@', [e description]); } @finally { [obj cleanUp]; }
and
MyClass *obj; @try { [obj doSomething]; } @catch (NSException * e) { NSLog(@'Exception occurred: %@', [e description]); } [obj cleanUp];
In what circumstances will the first snippet result in [obj cleanUp] being called, while the second won’t result in [obj cleanUp] being called? In other words, in what circumstances is @finally non-redundant when using Cocoa Exception Handling?
In that case, where you’re squashing the exception, none.
@finallyis used to clean up when you either don’t catch the exception, or rethrow it, in either case leaving final exception response to calling code. Since exceptions in Cocoa are only supposed to be used for programming errors and thus occur rarely, this is an entirely reasonably thing to do.It’s also worth pointing out one case where you don’t need to use
@finally, which is when you set up your own autorelease pool. When the “parent” autorelease pool is destroyed, any inner ones that haven’t been cleaned up yet will also be. If you do try to clean it up yourself, you need to promote the exception itself out of your autorelease pool.