Search code examples
iosnsexpression

Catching NSInvalidArgumentException from NSExpression


In my code I am evaluating strings as mathematical expressions for example:

NSString *formula=@"9*7";
NSExpression *expr =[NSExpression expressionWithFormat:formula];
NSLog(@"%@", [[expr expressionValueWithObject:nil context:nil]intValue]);

The above works fine but I will be handling dynamic input from users so I need to be able to catch the exception when the user enters faulty data, thus I need to be able to catch the exception in situations like the following:

NSString *formula=@"9*"; //note the deliberately invalid expression
NSExpression *expr =[NSExpression expressionWithFormat:formula];
@try {        
    [[expr expressionValueWithObject:nil context:nil]intValue];
}
@catch (NSException *exception) {
    NSLog(@"Exception");
}
@finally {
    NSLog(@"Finally");
}

However when I run this code I get:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "9* == 1"'

Is there some way to catch this exception? Or alternatively is there some way to test if an expression is valid before I pass it off?

Thanks!


Solution

  • The reason this exception is not caught with your current code is that the exception is being thrown from this line:

    NSExpression *expr =[NSExpression expressionWithFormat:formula];
    

    You need to move this line into the @try block.