views:

258

answers:

2

In my app I try to scroll a UITableView to the top once after I updated the content of the table. However, under some circumstance, my table is EMPTY. So I got the following exception:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: row (0) beyond bounds (0) for section (0).'

how can I catch this exception? I tried

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

if (indexPath != nil) {
    [EventTable scrollToRowAtIndexPath:indexPath
                atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

but it doesn't catch the exception because indexPath is not nil.

+2  A: 

Exception handling takes a different path than your typical flow control expressions. Apple has written up a useful article on Objective-C Exception Handling. Essentially you'll want to wrap your code in @try/@catch blocks. It is in the @catch block where you will receive the exception and perform the appropriate next steps in your code.

fbrereto
@try/@catch works but I always try to avoid using it. I think it is better to avoid the exception than catch it when it happens =) but thanks
Brian
Agreed- your question was asking specifically for how to catch the exception, not how to avoid it; I was trying to answer that for you.
fbrereto
+3  A: 

Before scrolling to an IndexPath, check your UITableView to make sure the row and section you're trying to scroll to are less than the number of rows and section in your table, respectively. If so, do not try to scroll to that IndexPath.

if ( [tableView numberOfSections] < section || [tableView numberOfRowsInSection] < row )
Tom S
Thanks. That's the way I do it.if (([EventTable numberOfSections] > 0) }
Brian
Sijo