赶上越界异常

时间:2013-03-31 06:34:33

标签: ios objective-c xcode

我是具有java先前知识的目标C的新手。我正在学习语言是如何工作的,我想知道如何在objective-c中捕获outOfBoundsExceptions?特别是数组。

示例:

NSString *stringReceivedServer=@"Jim 1551 error";
NSArray *split= [stringReceivedServer componentsSeparatedByString:""];
NSString *labelString= [split objectAtIndex:3] //Out of bounds

我做了这个例子,因为我将从服务器获取一些信息,我将获得如上所示的信息。有一个关于如何发送数据的标准,但有时可能会出错,因此如果字符串不是它应该是什么,我怎么能捕获错误?

谢谢!

2 个答案:

答案 0 :(得分:7)

首先,不要依赖异常处理,而只需 编写正确的代码。

其次,如果您感兴趣:可以使用NSException异常处理程序捕获@try-@catch-@finally

@try {
    id obj = [array objectAtIndex:array.count]; // BOOM
}
@catch (NSException *e) {
    NSLog(@"Got ya! %@", e);
}
@finally {
    NSLog(@"Here do unconditional deinitialization");
}

答案 1 :(得分:5)

与Java不同,由于Obj-C是C的超集,因此这里的出界不是错误。

这是逻辑错误,您需要处理自己的逻辑。

如,

NSString *labelString=nil;
if(split.count>3){
   labelString= [split objectAtIndex:3]; //Out of bounds
}
else{
    NSLog(@"out of bound");
}

或者你可以这样做:

@try {
   NSString *labelString = [split objectAtIndex:3];  
}
@catch (NSRangeEception * e) {
   NSLog(@"catching %@ reason %@", [e name], [e reason]);
}
@finally {
   //something that you want to do wether the exception is thrown or not.
}