Catching NSInvalidArgumentException from NSExpression

扶醉桌前 提交于 2019-12-02 02:46:18

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17287076/catching-nsinvalidargumentexception-from-nsexpression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!