0

I have the following object:

typedef void(^Block1)();
typedef void(^Block2)(Block1 block1);

@interface Test : NSObject
@end
@implementation Test
-(void)test:(Block2)block2 {
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    Block1 block1 = ^{
      // intentionally hold a ref of current object
      [self doNothing];
    };

    @try {
      block2(block1);
    } @catch (NSException *exception) {
      // do nothing
    }
  });
}
-(void)doNothing { }
-(void)dealloc{
  NSLog(@"deallocated: %@", self);
}
@end

And I use it like the following:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
      Test *t = [[Test alloc] init];
      [t test:^(Block1 block1) {
        // this @throw statement causes leak? 
        @throw [NSException exceptionWithName:@"ERROR" reason:nil userInfo:nil];
      }];
    }
    return 0;
}

If I @throw exception from Block2(As I did above), -dealloc method will never be called, If I do anything other than @throwing exceptions, everything works as expected.

Did I do anything wrong in the code or is this a bug?

neevek
  • 11,760
  • 8
  • 55
  • 73
  • Can't remember the source but ARC by default leaks with exception. You need to enable some flag to fix it. However because exception on ObjC normally means your app is about to crash, so it doesn't matter most of the time. – Bryan Chen Nov 08 '16 at 03:19
  • 2
    just find out my comments two years ago http://stackoverflow.com/questions/27140891/why-does-try-catch-in-objective-c-cause-memory-leak#comment42779256_27140891 – Bryan Chen Nov 08 '16 at 03:20
  • Don't throw exceptions in Objective-C except to deal with clear programming issues. Use "normal" error handling in Objective-C (such as a `nil` or `BOOL` return value and an `NSError` out-parameter just like in all of Apple's APIs. – rmaddy Nov 08 '16 at 03:24
  • @rmaddy _most_ of Apple's APIs – Bryan Chen Nov 08 '16 at 03:30
  • @BryanChen Do you have an example of Apple using a catchable exception that is actually used for proper error handling as opposed to exceptions being thrown due to programming errors? – rmaddy Nov 08 '16 at 03:33
  • @rmaddy `[NSFileHandle writeData:]` is one very frustrating example, along with most of `NSFileHandle`. (I am in no way disagreeing with your assertion about the correct use and meaning of exceptions.) – Rob Napier Nov 08 '16 at 03:36
  • @BryanChen, thanks for having found the duplicate, saved my day. – neevek Nov 08 '16 at 04:52

0 Answers0