问题描述
在我的代码中,我将字符串作为数学表达式进行评估,例如:
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:
有没有办法捕获此异常?或者是否有某种方法来测试表达式在我传递之前是否有效?
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?
谢谢!
推荐答案
此异常未被当前代码捕获的原因是该行引发了异常:
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];
您需要将此行移至 @try
阻止。
You need to move this line into the @try
block.
这篇关于从NSExpression捕获NSInvalidArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!