请看下面的代码。如果块[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");
}
}
答案 0 :(得分:1)
在completeAnimationClose
方法退出后,块将在单独的上下文中执行。这使它们处于不同的范围,使它们不再包含在@try {} @catch (..) {}
中。这意味着块中抛出的任何异常都不会被捕获,因为它们将在不同的上下文中执行。
附注:如果您期望动画或完成块中存在异常,则可能是您做错了。
第二方注意:将捕获同步块中的异常。例如:
@try {
NSArray *array = @[@(1), @(2)];
void (^test)() = ^{
[array objectAtIndex:3];
};
test();
}
@catch (NSException *exception) {
NSLog(@"Exception gets caught.");
}