NSExpression catch invalid arguments

南笙酒味 提交于 2019-12-06 06:34:43

问题


I am using NSExpression to evaluate a mathematical string and it works great. However I want to have a way of catching an error when the input string is invalid, such as "3++2". Is there a way to go about doing this instead of the application terminating due to 'NSInvalidArgumentException'. Sorry, I am fairly new to objective-c. The code I am using now is:

NSExpression *exp = [NSExpression expressionWithFormat: string];
NSNumber *result = [exp expressionValueWithObject:nil context:nil];
answer = [result stringValue];

回答1:


I think NSExpression is not the right tool for the job here. The class is part of the Cocoa predicate system and was designed to only accept well-formatted input.

I suggest you look for a proper math parser. I believe GCMathParser is a good choice. There's also DDMathParser.

If you insist on using NSExpression, you can catch the exception like this:

@try {
  // the code that potentially raises an NSInvalidArgumentException
} @catch (NSException *exception) {
  if ([[exception name] isEqualToString:NSInvalidArgumentException]) {
    // your error handling
  }
}

Be advised, however, that this is bad practice. Exceptions in Objective-C should only be used to catch unexpected runtime errors. Your example does not qualify.



来源:https://stackoverflow.com/questions/18421307/nsexpression-catch-invalid-arguments

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