如何获得引发异常的确切位置?

时间:2011-07-27 06:55:05

标签: iphone ipad exception exception-handling

我正在开发一个项目,在其中我在try块中放置了一段代码。

该块包含5个语句,以便将图像分配给imageView(我有5个图像视图,我从资源文件夹中添加图像)。如果资源文件夹中没有图像,则流程会跳转到catch块。

我想知道引发异常的五个中的确切陈述,以便我可以为nil分配图像。

@try {
    if (indexPath.row%2==0) {
        cell.bookImageView1.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+0].titleImage;
        cell.bookImageView2.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+1].titleImage;
        cell.bookImageView3.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+2].titleImage;
        cell.bookImageView4.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+3].titleImage;
        cell.bookImageView5.image=nil;
    }else {
        cell.bookImageView1.image=nil;
        cell.bookImageView2.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+0].titleImage;
        cell.bookImageView3.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+1].titleImage;
        cell.bookImageView4.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+2].titleImage;
        cell.bookImageView5.image=[[KitabooBookListDataSource sharedDataSource] bookAtIndex:(indexPath.row*4)+3].titleImage;
    }
}


@catch (NSException *e) {
    NSLog(@"catch block");
    NSLog(@"array of exception %@",[e callStackReturnAddresses]);
    //NSMutableArray *catchArray=[[NSMutableArray alloc] initWithArray:[e callStackReturnAddresses]];
    //[[catchArray lastObject] ]=nil;
}

1 个答案:

答案 0 :(得分:2)

通常不应该对程序流使用异常。相反,修改您的bookAtIndex:方法,以便在索引超出范围时返回nil ...或者更合适的是,您应该在尝试获取每本书之前检查书籍数量。

阅读my answer to this question了解有关异常和异常处理的更多信息。