try / catch周围包含块的整个方法是否会在块中捕获异常?

时间:2014-11-12 17:08:41

标签: ios objective-c

请看下面的代码。如果块[UIView animateWithDuration: animations:^{} completion:^(BOOL finished){}]中存在异常,那么(void)completeAnimationClose方法中的外部try / catch是否会捕获异常?

或者块需要自己独立的try / catch吗?

- (void)completeAnimationClose
{
    @try
    {
        self.fullImage.hidden = NO;
        [self.fullImageCopy removeFromSuperview];

        [UIView animateWithDuration:0.4
                         animations:^{self.bgView.alpha = 0.0;}
                         completion:^(BOOL finished){}];

        [UIView animateWithDuration:0.6
                         animations:^{

                             CGRect rect = [self.tableView convertRect:self.itemImageView.frame toView:nil];

                             self.bgView.frame = CGRectMake(rect.origin.x, rect.origin.y, self.itemImageView.frame.size.width, self.itemImageView.frame.size.height);
                             self.fullImage.frame = CGRectMake(rect.origin.x, rect.origin.y, self.itemImageView.frame.size.width, self.itemImageView.frame.size.height);
                             self.btnRemoveImage.frame = CGRectMake(rect.origin.x, rect.origin.y, self.itemImageView.frame.size.width, self.itemImageView.frame.size.height);

                         }
                         completion:^(BOOL finished){

                             [self.bgView removeFromSuperview];
                             [self.fullImage removeFromSuperview];
                             [self.btnRemoveImage removeFromSuperview];
                         }];
    }
    @catch (NSException *exception)
    {
        NSLog(@"CRASH");
    }
}

1 个答案:

答案 0 :(得分:1)

completeAnimationClose方法退出后,块将在单独的上下文中执行。这使它们处于不同的范围,使它们不再包含在@try {} @catch (..) {}中。这意味着块中抛出的任何异常都不会被捕获,因为它们将在不同的上下文中执行。

附注:如果您期望动画或完成块中存在异常,则可能是您做错了。

第二方注意:将捕获同步块中的异常。例如:

@try {
  NSArray *array = @[@(1), @(2)];
  void (^test)() = ^{
    [array objectAtIndex:3];
  };
  test();
}
@catch (NSException *exception) {
  NSLog(@"Exception gets caught.");
}