Alex Rivera | Logout

Does code in finally get run after a return in Objective-C?

Asked 2010-06-03T19:15:07.357
15

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.

Edit
Report

2 Answers

15

@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.

answered 2010-06-03T19:30:46.713
4

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.
answered 2010-06-03T19:32:42.490

Your Answer