Catching NSInvalidArgumentException from NSExpression
Asked Answered
W

2

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!

Ward answered 24/6, 2013 at 23:59 Comment(0)
C
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.

Cynthiacynthie answered 24/8, 2013 at 17:48 Comment(1)
Came back to this after awhile, and this totally works. Thanks.Ward
A
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.

Aesir answered 25/6, 2013 at 1:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.