@try - catch block in Objective-C

IphoneObjective CTry Catch-FinallyNsexception

Iphone Problem Overview


Why doesn't @try block work? It crashed the app, but it was supposed to be caught by the @try block.

 NSString* test = [NSString stringWithString:@"ss"];

 @try {
    [test characterAtIndex:6];

 }
 @catch (NSException * e) {
    NSLog(@"Exception: %@", e);
 }
 @finally {
    NSLog(@"finally");
 }

Iphone Solutions


Solution 1 - Iphone

All work perfectly :)

 NSString *test = @"test";
 unichar a;
 int index = 5;
    
 @try {
    a = [test characterAtIndex:index];
 }
 @catch (NSException *exception) {
    NSLog(@"%@", exception.reason);
    NSLog(@"Char at index %d cannot be found", index);
    NSLog(@"Max index is: %lu", [test length] - 1);
 }
 @finally {
    NSLog(@"Finally condition");
 }

Log:

> [__NSCFConstantString characterAtIndex:]: Range or index out of bounds > > Char at index 5 cannot be found > > Max index is: 3 > > Finally condition

Solution 2 - Iphone

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

Solution 3 - Iphone

Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandru CircusView Question on Stackoverflow
Solution 1 - IphoneiTuxView Answer on Stackoverflow
Solution 2 - IphoneAlexandru CircusView Answer on Stackoverflow
Solution 3 - IphoneThalliusView Answer on Stackoverflow