200

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");
 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Alexandru Circus
  • 5,478
  • 7
  • 52
  • 89
  • 2
    You can replace NSString* test = [NSString stringWithString:@"ss"]; with NSString* test = @"ss"; – Duyen-Hoa Jul 16 '14 at 12:21
  • Are you sure it is not something else because the exact code you have pasted above works fine. 2010-07-29 16:45:57.677 test[93103:207] Exception: *** -[NSCFString characterAtIndex:]: Range or index out of bounds 2010-07-29 16:45:57.678 test[93103:207] finally – mbogh Jul 29 '10 at 14:47

3 Answers3

148

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

Community
  • 1
  • 1
iTux
  • 1,946
  • 1
  • 16
  • 20
79

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
Alexandru Circus
  • 5,478
  • 7
  • 52
  • 89
  • 11
    IF you hit continue when the debugger breaks, you should see the exception gets thrown and caught by your handler. – JeremyP Jul 30 '10 at 12:17
0

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....

Thallius
  • 2,482
  • 2
  • 18
  • 36
  • Using try-catch in Objective-C is generally not recommended because it can potentially mess up the ARC. – slow Feb 12 '19 at 18:26