Duck
Duck

Reputation: 36013

Why is @try not working

I have a sensitive method that is doing operations with numbers and arrays. At one point I have something like this:

@try {

CGFloat value = [myArray[index] floatValue];

...

@catch (NSException *exception) {
   [self doSomething];
}

@finally {
}

If index is a negative value or a value out of myArray range, I want an exception to be thrown, or in other words, I want @catch to run, but it is not working, the app simply crashes when such conditions occur.

Yes, I know I can test the whole thing with if but I am trying to avoid using if (don't ask me why).

Why and how do I solve that?

Upvotes: 0

Views: 76

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

Objective-C does not raise exceptions when you access elements outside the range of built-in arrays; it remains undefined behavior - i.e. the way it is in "plain" C.

Using NSArray in place of a "plain C" array will fix the problem:

NSArray *myArray = @[@1, @3, @20];
@try {

CGFloat value = [myArray[index] floatValue];

...

@catch (NSException *exception) {
   [self doSomething];
}

@finally {
}

Upvotes: 1

jarmod
jarmod

Reputation: 78908

It crashes because the array in question does not range check the index. Only certain types of 'managed' arrays check the index. For example, NSArray will throw an NSRangeException. A regular C array such as int myarr[5] will not.

Upvotes: 2

Rufel
Rufel

Reputation: 2660

Well, I tried the following and successfully got the "exception!" printed out.

NSInteger i = -1;
NSArray *array = @[];
@try {
    CGFloat value = [array[i] floatValue];
}
@catch (NSException *e) {
    NSLog(@"exception!");
}

There is obviously something wrong in what you are doing (that you didn't put in your question).

Upvotes: 0

Related Questions