Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 771
Kevlar Avatar asked Jun 03 '10 19:06

Kevlar


People also ask

Does Finally still run after return?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

What happens when a finally block has a return statement?

Returning from inside a finally block will cause exceptions to be lost. A return statement inside a finally block will cause any exception that might be thrown in the try block to be discarded.

Can we have return statement after finally block?

Yes, we can write a return statement of the method in catch and finally block. There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.

Does finally always run?

A finally block always executes, regardless of whether an exception is thrown.


2 Answers

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

like image 89
progrmr Avatar answered Sep 27 '22 22:09

progrmr


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.
like image 41
lewiguez Avatar answered Sep 27 '22 21:09

lewiguez