Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what circumstances is @finally non-redundant in Cocoa's try/catch/finally Exception Handling?

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?

like image 510
Nick Forge Avatar asked Apr 12 '09 10:04

Nick Forge


2 Answers

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
like image 99
dstnbrkr Avatar answered Oct 13 '22 16:10

dstnbrkr


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.

like image 26
s4y Avatar answered Oct 13 '22 15:10

s4y