views:

95

answers:

2

consider the following code:

@try {
  if (something.notvalid)
  {
    return;
  }
  // do something else
} @catch (NSException *ex) {
  // handle exception
} @finally {
  NSLog(@"finally!");
}

if something is not valid and i return from within the try, does the code in @finally execute or not? I believe that it should but others I've spoken to don't think so and i'm unable to test this at the moment.

+2  A: 

@finally code always executes according to here and here.

A @finally block contains code that must be executed whether an exception is thrown or not.

progrmr
A: 

Yes. Oddly enough, it does. I'm not sure why, but I just built a test and tried a number of configurations and every time it did.

Here were the configs:

  • Return in try block: stopped execution of try block and caused finally to be executed
  • Return in try block and return in finally: stopped execution of try and stopped execution in finally block and the entire method.
  • Return in finally block: functioned like normal return outside of a try/catch/finally block.
lewiguez
The first case is not odd. That's the point of `finally`. See http://stackoverflow.com/questions/65035/in-java-does-return-trump-finally.
KennyTM
You see, I would expect for `return` to go beyond the scope of the `try/catch/finally` block and apply to the method. I'm not saying it's wrong that it does that, but it DID catch me off-guard. It's just something I've never paid attention to. I guess I've always carried my methods all the way through to the end ;)
lewiguez