简体   繁体   中英

@try @catch doesn't work objective-c

Running the code results in a crash.

 -(NSString*) ExtractStringKeyValue:(NSString*)key
{
    @try {
    NSRange  start = [_responceInfo rangeOfString:key];
    NSRange end  = [[_responceInfo substringFromIndex:start.location + start.length+2] 
                      rangeOfString:@"\""];

    NSRange rang = NSMakeRange(
                               start.location + start.length+1
                               , end.location+1);
    return [_responceInfo substringWithRange:rang];
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
    }
    @finally {
        NSLog(@"finally");
    }
}

Debug console:

2012-02-27 01:10:16.254 Clicky[8665:9203] Exception: * -[NSCFString substringFromIndex:]: Range or index out of bounds

2012-02-27 01:10:16.255 Clicky[8665:9203] finally

Help please.

As we can see the output in Console, your code goes through the @finally block:

2012-02-27 00:28:02.794 Clicky[8409:9203] finally

And according to the error message Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSCFString substringFromIndex:]: Range or index out of bounds' , I can tell you, that your problem is not in this method.

You're not returning anything from the method if the @try block fails, there's no string to return...

-(NSString*) ExtractStringKeyValue:(NSString*)key
{
    NSString *extractedString = nil;
    @try {
    NSRange  start = [_responceInfo rangeOfString:key];
    NSRange end  = [[_responceInfo substringFromIndex:start.location + start.length+2] 
                      rangeOfString:@"\""];

    NSRange rang = NSMakeRange(start.location + start.length+1, 
                               end.location+1);
    extractedString = [_responceInfo substringWithRange:rang];
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
    }
    @finally {
        NSLog(@"finally");
    }
    return extractedString;
}

I don't see substringFromIndex anywhere in the code you cut & pasted, so the reason why your @try / @catch block isn't working is because the Exception you see here is not coming from that code. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM