看下面的代码。如果[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");
    }
}

最佳答案

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

旁注:如果您希望动画或完成块中出现异常,则可能是做错了什么。

第二点说明:将捕获同步块中的异常。例:

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

关于ios - 是否可以对包含块的整个方法进行尝试/捕获而不会在块内捕获异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26892547/

10-11 23:11
查看更多