3

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!

Nathan Perry
  • 291
  • 2
  • 11

2 Answers2

8

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.

Steve Wilford
  • 8,894
  • 5
  • 42
  • 66
0

What you need is a maths parser. NSExpression was designed to take well-formed input, and doesn't handle errors. A quick Google will give this.

Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65