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 those scenarios there is no difference because the exception is swallowed. Here are two scenarios where there is a difference:
[obj cleanUp] is called:
MyClass *obj;
@try {
[obj doSomething];
}
@catch (NSException * e) {
@throw;
}
@finally {
[obj cleanUp]; // called when exception is caught
}
[obj cleanUp] is not called:
MyClass *obj;
@try {
[obj doSomething];
}
@catch (NSException * e) {
@throw;
}
[obj cleanUp]; // not called when exception is caught
It's also worth noting that code in @finally
blocks will run when control exits the @try
block for any reason, even via return
or goto
. For example:
@try {
doStuff();
if(bail){
return;
}
doMoreStuff();
}
@finally {
[obj cleanUp];
}
[obj announceSuccess];
[obj cleanUp]
will execute even if bail
is true, but [obj announceSuccess]
will not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With