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!